简体   繁体   English

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

[英]awk : convert first line to first column and second line to second column

I have a file with data something like this : 我有一个包含这样的数据的文件:

{
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
}

I want the output as : 我希望输出为:

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

and so on.. Any help is appreciated. 等等..任何帮助表示赞赏。

What I tried was: 我试过的是:

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

您能否尝试遵循并让我知道是否有帮助。

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

Solution with sed: 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 

Read and echo: 读取并回显:

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

code formatted: 代码格式:

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

暂无
暂无

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

相关问题 计算距离; 使用awk从第一行的第二列减去第二行的第一列 - calculate distance; substract the first column of the second line from the second column of the fist line using awk 使用awk将第二列移至第一列 - Moving the second column to first column using awk 使用带有多个分隔符的awk替换第一列的第二列 - replacing second column with first column using awk with multiple separators 如果第一列中的值匹配而第二列中的值与bash中另一个文件中的值不匹配,则提取行 - extract line if value in first column matches and value in second column not matches in another file in bash 将第一个字符串复制到第二行 - copying first string into second line 之后,使用awk打印第一列,第二列和每四列一次 - Use awk to print first column, second column and one column every four after that 如果第一列匹配则处理第二列 - process second column if first column matches 融合第一列的值,当第二列的值在 awk 或 bash 的不同文件中相同时,使用 awk 或 bash - Fuse values from first column, when the values from second column is the same in different files in awk or bash by using awk or bash 按数字排序按第二列排序,按字母顺序排序 - Sort according to second column numerically and first alphabetically 根据第一行过滤掉,然后使用它来获取第二行的数据 - Filtering out based on the first line, then using it to get the data of the second line
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM