bash Linux 命令行:拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1347822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linux command line: split a string
提问by Adam Matan
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.
它包含内核代码中的所有功能。记号是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.
我想将大约 100 个文件从内核目录复制到另一个目录,所以我想从函数名中去除每一行,只留下文件名。
It's super-easy in python, any idea how to write a 1-liner in the bash prompt that does the trick?
在 python 中非常简单,知道如何在 bash 提示中编写一个 1-liner 来实现这一点吗?
Thanks,
谢谢,
Udi
乌迪
回答by Eugene
cat "func_list" | sed "s#//.*##" > "file_list"
Didn't run it :)
没有运行它:)
回答by Paused until further notice.
You can use pure Bash:
您可以使用纯 Bash:
while read -r line; do echo "${line%//*}"; done < funclist.txt
Edit:
编辑:
The syntax of the echocommand is doing the same thing as the sedcommand in Eugene's answer: deleting the "//" and everything that comes after.
该echo命令的语法与sedEugene 的答案中的命令执行相同的操作:删除“//”以及后面的所有内容。
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 tosed's ".*"
"echo ${line}" 与 "echo $line" 相同,
如果
"%" 匹配参数的尾随部分,则 "%" 删除它后面的模式"%" 使匹配尽可能短,"%%" 使最长可能的
"//*" 是要匹配的模式,"*" 类似于sed's "。*"
See the Parameter Expansion section of the Bash manpage for more information, including:
有关man更多信息,请参阅 Bash页面的参数扩展部分,包括:
- using
${parameter#word}for matching the beginning of a parameter ${parameter/pattern/string}to dosed-style replacements${parameter:offset:length}to retrieve substrings- etc.
- 使用
${parameter#word}一个参数的开始匹配 ${parameter/pattern/string}做sed样式替换${parameter:offset:length}检索子串- 等等。
回答by ghostdog74
here's a one liner in (g)awk
这是 (g)awk 中的单衬
awk -F"//" '{print }' file

