Pau*_*son 4 grep sed text-processing
我有一组文本文件,其中包含的数据超出了我的需要。每个文件的第一行包含一个逗号分隔的字符串,如下所示:
stop_id,stop_code,stop_name,stop_desc,stop_lat,stop_lon,location_type,parent_station,zone_id
Run Code Online (Sandbox Code Playgroud)
然后,这些键下方是所有数据。我需要将该数据的一个子集提取到一个新的文本文件中,以便我可以使用该子集(我不需要所有数据,它太多了)。
我正在使用此命令来提取第一行:
sed -n '1p' source.txt > destination.txt
Run Code Online (Sandbox Code Playgroud)
我还使用此命令来提取我需要的特定行:
grep "string" source.txt > destination.txt
Run Code Online (Sandbox Code Playgroud)
挑战在于,当我在同一个脚本中运行这两个命令时(几乎按原样,用一行或 分隔&&),grep输出会覆盖sed输出。如何按顺序运行两者并获得两者的组合输出?
我注意到一个看起来相似的问题,涉及使用更复杂的grep命令来定位一行,然后是一系列行。这在这里不起作用,因为我需要从中提取数据的每个文件的第一行是不同的。
理想情况下,我想编写一个函数,我可以针对我需要处理的每个文件运行该函数,但我需要先链接这些命令并组合它们的输出。
Cyr*_*rus 10
sed可以做这两项工作(打印第一行和所有包含 的行string):
sed -n '1p; /string/p' source.txt > destination.txt
Run Code Online (Sandbox Code Playgroud)
或更长的版本:
sed -n -e '1p' -e '/string/p' source.txt > destination.txt
Run Code Online (Sandbox Code Playgroud)
有很多方法可以做到这一点。您可以使用单个命令来获取这两行,就像@Cyrus 的sed解决方案一样。以下是一些可以执行此操作的其他工具:
awk 'NR==1 || /string/' source.txt > destination.txt
perl -ne 'print if /string/ || $. ==1' source.txt > destination.txt
Run Code Online (Sandbox Code Playgroud)
您当然也可以运行您正在运行的两个命令,只需按照 BANJOSA 的建议将第二个命令更改为附加到文件中。或者,您可以将这两个命令分组到一个子外壳中,并将子外壳的输出重定向到一个文件:
(sed -n '1p' file; grep string file) source.txt > destination.txt
Run Code Online (Sandbox Code Playgroud)
或者
{ sed -n '1p' file; grep string file; } source.txt > destination.txt
Run Code Online (Sandbox Code Playgroud)
因此,如果您想做的是从这些中创建一个函数,只需将其添加到您的 shell 的初始化文件中(例如~/.bashrc):
foo(){ sed -n '1p' file; grep string file; }
Run Code Online (Sandbox Code Playgroud)
现在您可以运行该函数foo来执行您想要的操作:
foo source.txt > destination.txt
Run Code Online (Sandbox Code Playgroud)