所以,我上周开始学习bash,我必须完成一项任务,我应该打印这个file.txt
的内容:
1|george|01/02/2042
2|TPS Reports|03/01/2015
3|Go clubbing this weekend|
4|Metting with family|03/08/2015
5|Help Rose with dating boys|
6|Update hacking software for hacking StackExchange|09/30/2015
我写了这段代码:
while IFS='' read -r line || [[ -n $line ]]; do
IFS='|' read -ra ADDR <<< "$line"
echo -e "${ADDR[0]}: ${ADDR[1]} \t\t\t ${ADDR[2]}"
done < "$HOME_DIRECTORY_FILE"
所以,基本上这段代码将逐行进行,取每一行,然后使用分隔符|将其拆分为数组,然后在屏幕上打印数组的每个部分,输出:
1: george 01/02/2042
2: TPS Reports 03/01/2015
3: Go clubbing this weekend
4: Metting with family 03/08/2015
5: Help Rose with dating boys
6: Update hacking software for hacking StackExchange 09/30/2015
你可能认为这是正确的,但我的导师说日期必须在彼此之下,如下:
1: george 01/02/2042
2: TPS Reports 03/01/2015
3: Go clubbing this weekend
4: Metting with family 03/08/2015
5: Help Rose with dating boys
6: Update hacking software for hacking StackExchange 09/30/2015
这在bash中是否可以实现?或者我应该放弃这个?我的导师给出了确切的输出示例,以这种方式间隔并且说&#34;输出应该整齐地格式化(间隔)。&#34;
答案 0 :(得分:5)
使用column
命令。它完全符合您的需求。
例如:
$ cat input.txt
1|george|01/02/2042
2|TPS Reports|03/01/2015
3|Go clubbing this weekend|
4|Metting with family|03/08/2015
5|Help Rose with dating boys|
6|Update hacking software for hacking StackExchange|09/30/2015
$ column --separator \| --table input.txt
1 george 01/02/2042
2 TPS Reports 03/01/2015
3 Go clubbing this weekend
4 Metting with family 03/08/2015
5 Help Rose with dating boys
6 Update hacking software for hacking StackExchange 09/30/2015
您需要进行一些预先格式化以使您的号码为:
,但这应该是一个简单的部分(您可以将修改后的文件传输到column
)。
答案 1 :(得分:2)
您也可以使用printf
,但它需要您猜测中间列的宽度(column
为您计算)。
while IFS='' read -r line || [[ -n $line ]]; do
IFS='|' read -ra ADDR <<< "$line"
printf "%d: %-30s %s\n" "${ADDR[0]}" "${ADDR[1]}" "${ADDR[2]}"
done < "$HOME_DIRECTORY_FILE"