私はこのような入力を得ました:
ha lo
ha
ha lo
ha
ha
ha lo
2行目に文字列「lo」が含まれていない場合、どうすれば最後の行に行を追加できますか。後はこんな感じのはず
haha
hahaha
ha
これはなかなか難しいと思います。sed や awk でできるといいですね。
Here's one way to do it with GNU sed:
parse.sed
/ +lo/! H # Append to HS if / +lo/ doesn't match
/ +lo/ { # If it does match
s/ *lo// # remove it
x # put the rest in HS and contents of HS in PS
s/\n//g # Remove all newlines from PS
/./! t end # If PS empty jump to end
p # otherwise print
s/.*// # and empty it
}
$ { # If last line
x # swap PS/HS
s/\n//g # remove newlines
p # and print PS
}
: end
Run with:
sed -nr -f parse.sed < infile
Output:
haha
hahaha
ha
awk '
$2 == "lo" {if (line) print line; line = ""}
{line = line $1}
END {print line}
' filename
これは少し単純ですが、先頭の空白行が得られます
awk '$2 == "lo" {print ""} {printf("%s", $1)} END {print ""}'
ここに別の方法があります
file.txt には上記のエントリが含まれています
i=0;IFS=$'\n'; for line in `cat file.txt`; do ((i++)); if [[ [$line =~ lo ]]; then if [ $i -eq 1 ];then ha=$(echo "$line"|awk '{print $1}'); echo -n $ha; else echo; ha=$(echo "$line"|awk '{print $1}'); echo -n $ha; fi else echo -n "$line"; fi done; echo
ハハハハハ