Unix awk脚本将列转换为行

时间:2016-09-21 09:29:47

标签: unix awk

需要帮助才能在unix脚本中将行转换为列。我的来源是文件系统。

尝试以下脚本:

 `perl -nle '
    if($. == 1)
    { (@a)=/([\w - .]+)(?=,|\s*$)/g }
    else
    {
        (@b)=/([\w - .]+)(?=,|\s*$)/g;
        print "$a[0]|$b[0]|$b[1]|$b[2}|$a[$_]|$b[$_+3]" foreach (0..$#a)
    }
    ' ip.txt >op.txt

input data from file: 

src,FI,QMA,PCG,PCC,PREI,G T
PIM2016.csv,MMR.S T - RED,334,114,120,34,123,725

使用最新脚本输出:

  

SRC | PIM2016.csv | MMRPPS | RED | SRC | 334 SRC | PIM2016.csv | MMRPPS | RED | FI | 114   SDRC | PIM2016.csv | MMRPPS | RED | QMA | 120 SRC | PIM2016.csv | MMRPPS | RED | PCG | 34   SRC | PIM2016.csv | MMRPPS | RED | PCC | 123 SRC | PIM2016.csv | MMRPPS | RED | PREI | 725   SRC | PIM2016.csv | MMRPPS | RED | G T |

必需的输出:

  

SRC | PIM2016.csv | MMRPPS | S T -RED | FI | 334 SRC | PIM2016.csv | MMRPPS | S T   -RED | QMA | 114 SRC | PIM2016.csv | MMRPPS | S T -RED | PCG | 120 SRC | PIM2016.csv | MMRPPS | S T -RED | PCC | 34 SRC | PIM2016.csv | MMRPPS | S T   -RED | PREI | 123 SRC | PIM2016.csv | MMRPPS | S T -RED | G T | 725

2 个答案:

答案 0 :(得分:0)

$ cat ip.txt 
HDR :FI,QA,PC,PM,PRE,G T
Detail row: MMRPPS,ST - RED,334,114,120,34,123,725
            UP,UPR,0,0,0,0,0,0

假设行之间没有空行:

$ perl -nle '
s/^.*:\s*|^\s*|\s*$//;
if($. == 1)
{ (@a) = /[^,]+/g }
else
{
    (@b) = /[^,]+/g;
    print "$b[0] $a[$_] $b[1] $b[$_+2]" foreach (0..$#a);
}
' ip.txt
MMRPPS FI ST - RED 334
MMRPPS QA ST - RED 114
MMRPPS PC ST - RED 120
MMRPPS PM ST - RED 34
MMRPPS PRE ST - RED 123
MMRPPS G T ST - RED 725
UP FI UPR 0
UP QA UPR 0
UP PC UPR 0
UP PM UPR 0
UP PRE UPR 0
UP G T UPR 0
  • 预处理输入行以删除前导文本:,任何前导和尾随空格
  • 从第一行开始,将逗号分隔值提取到@a数组中。正则表达式查找非,个字符串
  • 对于所有其他线路,
    • 相同的正则表达式将逗号分隔值提取到@b数组
    • 按所需顺序打印

答案 1 :(得分:0)

@sundeep:谢谢你的回答。下面的脚本工作

ErrorDocument 404     /404
ErrorDocument 500     /500
Options +FollowSymLinks -MultiViews

RewriteEngine On

RewriteRule ^(resources)($|/) - [L]

RewriteRule ^user/([^/]+)/?$ /users.php?user=$1 [L]

RewriteRule ^dev/([^/]+)/?$ /dev.php?type=$1 [L]

RewriteRule ^(users|settings|groups|page)/([^/]+)/?$ /$1.php?view=$2 [L,QSA,NC]

RewriteRule ^(users|groups)/(\w+)/([^/]+)/?$ /$1.php?view=$2&id=$3 [L,QSA,NC]

# To internally redirect /dir/file to /dir/file.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]