Linux command line: split a string

15,877

Solution 1

cat "func_list" | sed "s#//.*##" > "file_list"

Didn't run it :)

Solution 2

You can use pure Bash:

while read -r line; do echo "${line%//*}"; done < funclist.txt

Edit:

The syntax of the echo command is doing the same thing as the sed command in Eugene's answer: deleting the "//" and everything that comes after.

Broken down:

"echo ${line}" is the same as "echo $line"
the "%" deletes the pattern that follows it if it matches the trailing portion of the parameter
"%" makes the shortest possible match, "%%" makes the longest possible
"//*" is the pattern to match, "*" is similar to sed's ".*"

See the Parameter Expansion section of the Bash man page for more information, including:

  • using ${parameter#word} for matching the beginning of a parameter
  • ${parameter/pattern/string} to do sed-style replacements
  • ${parameter:offset:length} to retrieve substrings
  • etc.

Solution 3

here's a one liner in (g)awk

awk -F"//" '{print $1}' file
Share:
15,877
Adam Matan
Author by

Adam Matan

Team leader, developer, and public speaker. I build end-to-end apps using modern cloud infrastructure, especially serverless tools. My current position is R&amp;D Manager at Corvid by Wix.com, a serverless platform for rapid web app generation. My CV and contact details are available on my Github README.

Updated on June 08, 2022

Comments

  • Adam Matan
    Adam Matan almost 2 years

    I have long file with the following list:

    /drivers/isdn/hardware/eicon/message.c//add_b1()
    /drivers/media/video/saa7134/saa7134-dvb.c//dvb_init()
    /sound/pci/ac97/ac97_codec.c//snd_ac97_mixer_build()
    /drivers/s390/char/tape_34xx.c//tape_34xx_unit_check()
    (PROBLEM)/drivers/video/sis/init301.c//SiS_GetCRT2Data301()
    /drivers/scsi/sg.c//sg_ioctl()
    /fs/ntfs/file.c//ntfs_prepare_pages_for_non_resident_write()
    /drivers/net/tg3.c//tg3_reset_hw()
    /arch/cris/arch-v32/drivers/cryptocop.c//cryptocop_setup_dma_list()
    /drivers/media/video/pvrusb2/pvrusb2-v4l2.c//pvr2_v4l2_do_ioctl()
    /drivers/video/aty/atyfb_base.c//aty_init()
    /block/compat_ioctl.c//compat_blkdev_driver_ioctl()
    ....
    

    It contains all the functions in the kernel code. The notation is file//function.

    I want to copy some 100 files from the kernel directory to another directory, so I want to strip every line from the function name, leaving just the filename.

    It's super-easy in python, any idea how to write a 1-liner in the bash prompt that does the trick?

    Thanks,

    Udi