我正在努力捕捉文件,同时打印出一些文字。
例如:
/ root / file包含:
line1
line2
line3
脚本:
#!/bin/bash
echo -en "Printing Line of the file: `cat /root/file`\n"
结果:
Printing Line of the file: line1
line2
line3
预期结果:
Printing Line of the file: line1
line2
line3
如何获得我想要的输出?
答案 0 :(得分:2)
只是打击:
(
first="Printing Line of the file:"
IFS=
read -r line
printf "%*s %s\n" ${#first} "$first" "$line"
while read -r line; do
printf "%*s %s\n" ${#first} "" "$line"
done
) < file
Printing Line of the file: line1
line2
line3
使用printf,您可以使用*
作为字段宽度,然后在参数中提供一个数字。我在子shell中运行它,因此更改IFS
不会影响父shell。
使用标签实现您的书面目标:
echo "Printing Line of the file: $(awk -v ORS="\n\t\t\t" 1 file)"
答案 1 :(得分:0)
您可以使用以下现有实用程序:
myvar="Printing Line of the file: "
size=${#myvar}
# getting the right size is the tricky part
var_final_size=$((size+5))
echo -en "${myvar}`awk -F\; -v fmt="%${var_final_size}s\n" '{if (NR==1) {print $1} else {printf fmt, $1}}' test.txt`\n"
或者你可以编写这样的脚本:
#!/bin/bash
myvar="Printing Line of the file: "
size=${#myvar}
var_counter=0
for r in `cat /root/file`
do
var_size=${#r}
var_final_size=$((size+var_size))
if [ $var_counter -eq 0 ]; then
printf "%${var_final_size}s\n" "${myvar}${r}"
else
printf "%${var_final_size}s\n" "${r}"
fi
var_counter=$((var_counter+1))
done
输出
Printing Line of the file: line1
line2
line3
答案 2 :(得分:0)
echo -en "Printing Line: `awk '{if (NR==1) {print " "$0} else {print "\t\t\t"$0}}' file`\n"
Printing Line: line1
line2
line3
(这似乎有效,即使它已经嵌套了#34;内部&#34;&#34;,它可能需要print \" \"$0
并且类似于正确地逃避它们,我不会#39; t know)。
答案 3 :(得分:0)
以下逐行打印 - 右对齐32个字符:
awk '{ printf("%32s\n", $0) }'
假设长度相同......我们可以在第一行达到峰值,计算字符并在所有行上设置printf的模式。
awk 'NR==1 { f = "%" length "s\n" } { printf(f, $0) }'
如果行长度不同,可以使用相同的构思与sprintf创建空间的 pad :
awk -v x='Printing Line of the file: ' 'NR==1 { pad = sprintf("%" length(x) "s", ""); print x $0; next } { print pad $0 }' /root/file