大家希望下面的内容有道理。
我有一个包含大量垃圾的文件以及我希望保留的一些数据,我希望提取的数据是包含" =>"的任何行。加上前一行,我的问题是我真的需要输出(包含=>和上一行的行)包含在同一行 例如:
junk
input <= lala
thing1 => lululu
more junk
more junks
even more junks
input <= junk
extra junk
hello123 => lelele
input <= lololo
thing3 => kt
我目前使用的是&#34; grep -B 1&#39; =&gt;&#39;文件1&#34;是:
input <= lala
thing1 => lululu
--
extra junk
hello123 => lelele
--
input <= lololo
thing3 => kt
我真正想要的是或类似的东西。
input <= lala thing1 => lululu
--
extra junk hello123 => lelele
--
input <= lololo thing3 => kt
答案 0 :(得分:0)
假设你正在使用bash,你可以在一行中完成:
t="";for i in $(grep -B 1 '=>' tmp.txt) ; do if [[ "$i" != "--" ]] ;then t="$t $i"; else echo "$t";echo "--";t="";fi;done;echo "$t"
输出:
alfasi$ t="";for i in $(grep -B 1 '=>' tmp.txt) ; do if [[ "$i" != "--" ]] ;then t="$t $i"; else echo "$t";echo "--";t="";fi;done;echo "$t"
input <= lala thing1 => lululu
--
extra junk hello123 => lelele
--
input <= lololo thing3 => kt
lgml-alfasi2:bin alfasi$
答案 1 :(得分:0)
使用here string
然后在toggle
循环内使用while
来阅读输入的过程并不困难。有许多不同的方法可以做到这一点。这首先想到了。
#!/bin/bash
# read input filename as first argument
ifn="$1"
# validate file is readable
[ -r "$ifn" ] || {
printf "error: file not readable '%s'.\n" "$ifn"
exit 1
}
declare -i a=0 # use 'a' as first/second line toggle
## for each line in results
while read -r line; do
[ ${line:0:1} == '-' ] && { a=0; continue; } # skip -- lines
[ $a -eq 0 ] && sav="$line" # if a=0, save line
if [ $a -eq 1 ]; then # if a=1, form output
myline="${sav} ${line}"
# printf -- "--\n" # uncomment for separator
printf "%s\n" "$myline"
fi
[ $a -eq 0 ] && a=1 || a=0 # toggle a=0/1
done <<< "$(grep -B 1 '=>' "$ifn")"
exit 0
<强>输入强>
$ cat dat/twotoone.dat
junk
input <= lala
thing1 => lululu
more junk
more junks
even more junks
input <= junk
extra junk
hello123 => lelele
input <= lololo
thing3 => kt
<强>输出强>
$ bash twointoone.sh dat/twotoone.dat
input <= lala thing1 => lululu
extra junk hello123 => lelele
input <= lololo thing3 => kt
注意:如果您希望这些行之间有分隔符,请在打印$myline
之前添加以下内容:
printf -- "--\n"
带分隔符的输出
$ bash twointoone.sh dat/twotoone.dat
--
input <= lala thing1 => lululu
--
extra junk hello123 => lelele
--
input <= lololo thing3 => kt
答案 2 :(得分:0)
这与awk
awk '/=>/ {print a,$0"\n--"} {a=$0}' file
input <= lala thing1 => lululu
--
extra junk hello123 => lelele
--
input <= lololo thing3 => kt
--
如果您不喜欢要打印的最后一个--
:
awk '/=>/ {print (f++?"--\n":"")a,$0} {a=$0}' file
input <= lala thing1 => lululu
--
extra junk hello123 => lelele
--
input <= lololo thing3 => kt