繁体   English   中英

解析另一个文件后,在文件中获取第N行

[英]get Nth line in file after parsing another file

我有一个大文件

foo:43:sdfasd:daasf
bar:51:werrwr:asdfa
qux:34:werdfs:asdfa
foo:234:dfasdf:dasf
qux:345:dsfasd:erwe
...............

这里第一列foo,bar和qux等是文件名。 第二列43,41,34等是行号。 我想为每个文件打印第N行(由第2列指定)(在第1列中指定)。 如何在unix shell中自动执行上述操作。 实际上上面的文件是在编译时生成的,我想在代码中打印警告线。

-谢谢,

while IFS=: read name line rest
do
    head -n $line $name | tail -1
done < input.txt

while IFS=: read file line message; do
    echo "$file:$line - $message:"
    sed -n "${line}p" "$file"
done <yourfilehere
awk 'NR==4 {print}' yourfilename

or

cat yourfilename | awk 'NR==4 {print}'

上面的内容适用于您文件中的第4行。您可以根据需要更改数字。

 sed -nr '3{s/^([^:]*):([^:]*):.*$/\1 \2/;p}' namesNnumbers.txt 
 qux 34
  • -n默认没输出,
  • -r正则表达式(简化使用parens)
  • 在第3行做{...; p}(打印到底)
  • 与foo酒吧合作的foobarbaz

所以要使用这些值:

fnUln=$(sed -nr '3{s/^([^:]*):([^:]*):.*$/\1 \2/;p}' namesNnumbers.txt)

fn=$(echo ${fnUln/ */})
ln=$(echo ${fnUln/* /})
sed -n "${ln}p" "$fn"

只是在awk中,但可能比@kev或@MarkReed的答案更糟糕。 但它只会处理每个文件一次。 需要GNU awk

gawk -F: '
    BEGIN {OFS=FS}
    { 
        files[$1] = 1
        lines[$1] = lines[$1] " " $2
        msgs[$1, $2] = $3 
    }
    END {
        for (file in files) {
            split(lines[file], l, " ")
            n = asort(l)
            count = 0
            for (i=1; i<=n; i++) {
                while (++count <= l[i])
                    getline line < file
                print file, l[i], msgs[file, l[i]]
                print line
            }
            close(file)
        }
    }
'

这可能对你有用:

sed 's/^\([^,]*\),\([^,]*\).*/sed -n "\2p" \1/' file |
sort -k4,4 | 
sed ':a;$!N;s/^\(.*\)\(".*\)\n.*"\(.*\)\2/\1;\3\2/;ta;P;D' |
sh

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM