awk:将第一行转换为第一列,将第二行转换为第二列

时间:2018-03-23 06:23:03

标签: bash shell awk

我有一个包含以下数据的文件:

{
MAG 121/002
Wed Mar 14 00:00:00 2018
MAG 121/003
Wed Mar 14 00:00:00 2018
MAG 121/004
Wed Mar 14 00:00:00 2018
}

我希望输出为:

{
MAG 121/002 | Wed Mar 14 00:00:00 2018
MAG 121/003 | Wed Mar 14 00:00:00 2018
}

依此类推。感谢任何帮助。

我尝试的是:

cat <filename> | awk '{printf "%s" (NR%2==0? RS:FS), $1}'

3 个答案:

答案 0 :(得分:2)

如果有帮助,请您试试并告诉我。

awk '/{/||/}/{print;next} /MAG/{val=$0;getline;print val OFS $0}' OFS=" | "  Input_file

答案 1 :(得分:0)

使用sed解决方案:

echo "MAG 121/002
Wed Mar 14 00:00:00 2018
MAG 121/003
Wed Mar 14 00:00:00 2018
MAG 121/004
Wed Mar 14 00:00:00 2018" | tr "\n" "|" | sed 's/|/ | /g' | sed -r 's/([^|]+\|[^|]+)\| /\1\n/g'
MAG 121/002 | Wed Mar 14 00:00:00 2018 
MAG 121/003 | Wed Mar 14 00:00:00 2018 
MAG 121/004 | Wed Mar 14 00:00:00 2018 

答案 2 :(得分:0)

阅读并回复:

echo "MAG 121/002
Wed Mar 14 00:00:00 2018
MAG 121/003
Wed Mar 14 00:00:00 2018
MAG 121/004
Wed Mar 14 00:00:00 2018" | while read line ; do case $line in MAG*) echo -n $line "| " ;; *) echo $line ;; esac ; done 
MAG 121/002 | Wed Mar 14 00:00:00 2018
MAG 121/003 | Wed Mar 14 00:00:00 2018
MAG 121/004 | Wed Mar 14 00:00:00 2018

代码格式化:

while read line
do
  case $line in 
    MAG*) echo -n $line "| " ;; 
       *) echo $line ;; 
  esac
done