如何使用bash替换在列表的每个元素的末尾附加换行符

时间:2014-12-08 16:29:35

标签: bash

我正在寻找一个bash one liner,它在列表的每个元素后附加一个换行符。如果我将脚本称为:

./script arg1 arg2 arg3

我希望输出为

arg1
arg2
arg3

我尝试了以下不同的变体。换行没有添加。任何普通的char都会被添加。

# pretty much works except for an extra space
list=${@/%/x}
echo "$list"

# appends 'n'
list=${@/%/\n}
echo "$list"

# appends nothing
list=${@/%/$'\n'}
echo "$list"

# appends nothing, \x078 would append 'x'
list=${@/%/$'\x0D'}
echo "$list"

# appends nothing
CR=$'\n'
list=${@/%/$CR}
echo "$list"

# same issues with arrays
tmp=($@)
list=${tmp/%/\n}
echo "$list"

您建议使用哪种方法或替代方案?我显然可以写一个循环或调用tr,但这正是我认为我可以通过bash替换避免的。

2 个答案:

答案 0 :(得分:5)

您可以将此功能与"$@"

一起使用
f() { printf "%s\n" "$@"; }
f arg1 arg2 arg3
arg1
arg2
arg3

根据man bash

 @   Expands  to  the positional parameters, starting from one.  When the expansion occurs
     within double quotes, each parameter expands to a separate word.  That is, "$@" is
     equivalent to "$1" "$2" ...

答案 1 :(得分:2)

printf也是我的答案。另一种技术是使用IFS

$ IFS=$'\n'
$ list="$*"
$ echo "$list"
arg1
arg2
arg3

注意:

  • 使用ANSI-C引用换行符序列
  • "$*"with the quotes,critical)使用$ IFS的第一个字符加入位置参数
  • 引用echo命令的shell变量来保留内部换行符。

重新定义当前shell的IFS值。您可以先保存旧值,然后在以下位置恢复:

oldIFS=$IFS; IFS=$'\n'; list="$*"; IFS=$oldIFS

或者您可以使用子shell,以便为您丢弃修改:

$ list=$( IFS=$'\n'; echo "$*" )