0

如何使用 unix shell 脚本 awk 从文本文件中提取一些行。

例如 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 中。并在腻子中返回这些行:

awk: Field $() is not correct.
The input line number is 2. The file is file_name_test.txt
The source line number is 2.

任何的想法?谢谢你。

4

3 回答 3

1

让我先修复你的脚本:

#!/bin/bash
FILENAME=$1
THRESHOLD=$2

awk -v t=$THRESHOLD '{
        lc++;
        if (lc == 1 || lc > t) {
                print $0;
        }
}' $FILENAME
于 2012-12-03T11:29:23.620 回答
0

您需要将 shell 变量传递给awkusing-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
于 2012-12-03T11:30:19.170 回答
0

这是类似于 glenn jackman 的解决方案的 Perl 代码:

perl -slne 'print if $. == 1 or $. >= $n' -- -n=15 

$.是行号

于 2015-09-14T22:46:33.010 回答