如何使用unix shell脚本awk从文本文件中提取一些行。
e.g。 1)输入:file_name_test.txt
**<header> asdfdsafdsf**
11 asd sad
12 sadf asdf
13 asdfsa asdf
14 asd sdaf
**15 asd asdfsdf
16 sadfsadfsaf sdfsdf
17 asdf sdaf
18 asfd saf
19 sadf asdf
10 asf asf**
2)预期产出:
**<header> asdfdsafdsf
15 asd asdfsdf
16 sadfsadfsaf sdfsdf
17 asdf sdaf
18 asfd saf
19 sadf asdf
10 asf asf**
3)test.sh的代码:
FILENAME=$1
threshold=$2
awk '{line_count++;
if (line_count==1 || (line_count>$threshold))
print $0;
}' $FILENAME > overflow_new2
4)
sh test.sh file_name_test.txt 5
5)它只打印第一行:
<header> asdfdsafdsf
在输出文件overflow_new2中。并在putty中返回这些行:
awk: Field $() is not correct.
The input line number is 2. The file is file_name_test.txt
The source line number is 2.
有什么想法吗?谢谢。
答案 0 :(得分:1)
让我先修复你的脚本:
#!/bin/bash
FILENAME=$1
THRESHOLD=$2
awk -v t=$THRESHOLD '{
lc++;
if (lc == 1 || lc > t) {
print $0;
}
}' $FILENAME
答案 1 :(得分:0)
您需要使用awk
标志将shell变量传递给-v
:
filename=$1
threshold=$2
awk -v thres="$threshold" '
{ line_count++ }
line_count==1 || line_count > thres { print }
' $filename > overflow_new2
运行时如下:
./script.sh file_name_test.txt 5
overflow_new2
的结果/内容:
**<header> asdfdsafdsf**
**15 asd asdfsdf
16 sadfsadfsaf sdfsdf
17 asdf sdaf
18 asfd saf
19 sadf asdf
10 asf asf**
另外,为了准确再现所需的结果,这就是我的方式:
filename=$1
threshold=$2
awk -v thres="$threshold" '
FNR == 1 {
sub(/**\s*$/,"")
print
}
FNR > thres {
sub(/^**/,"")
print
}
' $filename > overflow_new2
答案 2 :(得分:0)
这里的Perl代码类似于glenn jackman的解决方案:
perl -slne 'print if $. == 1 or $. >= $n' -- -n=15
$.
是行号