[英]Using SED/AWK, extract lines from text file where line have N common words with previous line
[英]Copy value from previous line using awk/sed
有什么想法如何編寫awk / sed腳本來替換特定的哨兵值或模式(在這種情況下,是從與上一行不同的列中的值進行PREV
嗎?)
例如,替換上一行第一列中的值的所有PREVs
a -> b
c -> PREV
d -> PREV
至:
a -> b
c -> a
d -> c
$ awk 'NR>1{$3=p} {p=$1} 1' file
a -> b
c -> a
d -> c
$ cat file
a -> b
c -> PREV
d -> PREV
e -> f # watch this record
g -> PREV
要使用awk 替換PREV
一行第一列中的值的所有PREV
:
$ awk '$3=="PREV"{$3=prev}{prev=$1}1' file
輸出:
a -> b
c -> a
d -> c
e -> f # watch this record
g -> e
高爾夫:
$ awk '$3=p?p:$3; {p=$1}' file
a -> b
c -> a
d -> c
占$1==0
:
$ awk '$3 = length(p)? p: $3; {p=$1}' <<EOF
a -> b
c -> PREV
d -> PREV
0 -> PREV
e -> PREV
f -> PREV
EOF
a -> b
c -> a
d -> c
0 -> d
f -> e
使用GNU sed:
sed -E '/PREV/{G;s/PREV(.*)\n(\S+).*/\2\1/};h' infile
解釋:
/PREV/ { # if the current line matches PREV
G # append hold space to pattern space
s/PREV(.*)\n(\S+).*/\2\1/ # replace PREV with first word from appended line,
# drop newline and rest of appended line
}
h # store pattern space in hold space
或者,對可移植性進行了一些修改:
sed '/PREV/{G;s/PREV\(.*\)\n\([^[:blank:]]\{1,\}\).*/\2\1/;};h' infile
如果您的數據在d
文件中,請嘗試使用gnu sed:
sed -Ez ':s s/((\S+)\s*->[^\n]+\n[^\n]*)PREV\s*/\1\2\n/;ts' d
對於此內容
$ cat file
a -> b
c -> PREV
d -> PREV
e -> PREV
g -> GOLD
p -> m
確保僅更換PREV前哨(其他保持原樣):
$ awk 'NR>1 && /PREV/{$3=p}{p=$1} 1' file
a -> b
c -> a
d -> c
e -> d
g -> GOLD
p -> m
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.