Pau*_*aul 147 bash shell-script text-processing
我有多个文件在前 5-10 行中包含 ascii 文本信息,然后是列表良好的矩阵信息。在 shell 脚本中,我想删除前几行文本,以便我可以在另一个程序中使用纯矩阵信息。如何使用 bash shell 命令来执行此操作?
如果有任何帮助,我正在使用 RedHat 和 Ubuntu linux 系统。
Ign*_*ams 228
只要文件不是符号链接或硬链接,就可以使用 sed、tail 或 awk。下面举例。
$ cat t.txt
12
34
56
78
90
Run Code Online (Sandbox Code Playgroud)
$ sed -e '1,3d' < t.txt
78
90
Run Code Online (Sandbox Code Playgroud)
您还可以在没有临时文件的情况下就地使用 sed:sed -i -e 1,3d yourfile. 这不会回显任何内容,它只会就地修改文件。如果您不需要将结果通过管道传送到另一个命令,这会更容易。
$ tail -n +4 t.txt
78
90
Run Code Online (Sandbox Code Playgroud)
$ awk 'NR > 3 { print }' < t.txt
78
90
Run Code Online (Sandbox Code Playgroud)
alh*_*lal 32
sed -i '1,3d' file.txt
这将从 file.txt 中删除前 3 行。
如果列表行是具有制表符的行:
grep '?' <input_file >output_file
Run Code Online (Sandbox Code Playgroud)
(?作为文字制表符)或等效
sed -n '/?/p' <input_file >output_file
Run Code Online (Sandbox Code Playgroud)
在 bash/ksh/zsh 脚本中,您可以$'\t'为选项卡编写,例如grep $'\t'或sed -n $'/\t/p'。
如果要删除文件开头的 10 行:
tail -n +11 <input_file >output_file
Run Code Online (Sandbox Code Playgroud)
(请注意,这是+11消除 10 行,因为+11表示“从第 11 行开始”和从 1 开始的尾数行)或
sed '1,10d' <input_file >output_file
Run Code Online (Sandbox Code Playgroud)
在 Linux 上,您可以利用 GNU sed 的-i选项来修改文件:
sed -i -n '/\t/p' *.txt
Run Code Online (Sandbox Code Playgroud)
或者您可以使用 shell 循环和临时文件:
for x in *.txt; do
tail -n +11 <"$x" >"$x.tmp"
mv "$x.tmp" "$x"
done
Run Code Online (Sandbox Code Playgroud)
或者,如果您不想就地修改文件,而是给它们一个不同的名称:
for x in *.txt; do
tail -n +11 <"$x" >"${x%.txt}.data"
done
Run Code Online (Sandbox Code Playgroud)
您可以在 Ex 模式下使用 Vim:
ex -s -c '1d5|x' file
Run Code Online (Sandbox Code Playgroud)
1移至第一行
5选择5行
d删除
x保存并关闭