Linux/bash 中的一行代码打印复杂的语句

Linux/bash 中的一行代码打印复杂的语句

我有一个包含两列数据的文件,比方说:

kevin n1

edwin n2

mevin n3

我想生成一个类似这样的声明。

--This is kevin and his 'roll number' is n1

--This is edwin and his 'roll number' is n2

--This is mewin and his 'roll number' is n3

现在,我无法用 来做到这一点awk。它不喜欢在语句中间使用虚线“--”或单引号(')。

我希望输出像上面所示的那样?

答案1

使用 awk:

awk 'NF{print "--This is " $1 " and his \047roll number\047 is " $2 }' file

\047是单引号的八进制代码'

另一种选择是定义一个包含单引号字符的变量:

awk -v sq="'" 'NF{print "--This is " $1 " and his "sq"roll number"sq" is " $2 }' file

答案2

简单while循环:

while read -r name roll; do if [[ -z "$name" ]]; then echo ; else echo "--This is $name and his 'roll number' is $roll"; fi; done < infile
--This is kevin and his 'roll number' is n1

--This is edwin and his 'roll number' is n2

--This is mevin and his 'roll number' is n3

这个解决方案保留了空白行,因为这似乎是OP的愿望。

infile如下所示:

cat infile 
kevin n1

edwin n2

mevin n3

这没有错误处理等,当然取决于 OP 指定的文件格式。

答案3

Perl 一行:

perl -ane '@F && printf "--This is %s and his '\''roll number'\'' is %s\n", @F' file

相关内容