如何通过bash脚本交换偶数行和奇数行?
在来自标准输入的传入字符串流中,交换偶数行和奇数行。
我尝试这样做,但是从文件读取和 $i -lt $a.count
不起作用:
$a= gc test.txt
for($i=0;$i -lt $a.count;$i++)
{
if($i%2)
{
$a[$i-1]
}
else
{
$a[$i+1]
}
}
请帮助我让它工作
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
建议一行
awk
脚本:awk
脚本说明Suggesting one line
awk
script:awk
script explanation这里已经有一个很好的基于 awk 的答案,并且在 sed 和
awk
解决方案="https://www.theunixschool.com/2012/06/swap-every-2-lines-in-file.html" rel="nofollow noreferrer">在文件中每 2 行交换。然而,中的shell解决方案每2行交换一次在文件中几乎是可笑的无能。下面的代码是对功能正确的纯 Bash 解决方案的尝试。 Bash 非常慢,因此只适用于小文件(可能最多 10,000 行)。lines
数组用于保存两个连续的行。IFS=
防止在读取行时删除空格。idx
变量循环0, 1, 0, 1, ...
(idx=$(( (idx+1)%2 ))
code>),因此读取lines[idx]
时会循环将输入行置于lines
0 和1
处> 数组。read
是否实际读取了某些输入来避免这种情况。 (幸运的是,文件末尾不存在未终止的空行。)printf
而不是echo
来输出行,因为echo< /code> 对于任意字符串不能可靠地工作。 (例如,仅包含
-n
的行将因echo "$line"
而完全丢失。)请参阅 为什么 printf 比 echo 更好?。(( idx == 1 )) && printf '%s\n' "${lines[0]}"
) 只是传递交换行之后的最后一行。其他合理的选择是删除最后一行或在其前面添加一个额外的空行。如果需要,可以轻松修改代码以执行其中一项操作。There's already a good
awk
-based answer to the question here, and there are a few decent-lookingsed
andawk
solutions in Swap every 2 lines in a file. However, the shell solution in Swap every 2 lines in a file is almost comically incompetent. The code below is an attempt at a functionally correct pure Bash solution. Bash is very slow, so it is practical to use only on small files (maybe up to 10 thousand lines).lines
array is used to hold two consecutive lines.IFS=
prevents whitespace being stripped as lines are read.idx
variable cycles through0, 1, 0, 1, ...
(idx=$(( (idx+1)%2 ))
) so reading tolines[idx]
cycles through putting input lines at indexes0
and1
in thelines
array.read
function returns non-zero status immediately if it encounters an unterminated final line in the input. That could cause the loop to terminate before processing the last line, thus losing it in the output. The|| [[ -n ${lines[idx]} ]]
avoids that by checking if theread
actually read some input. (Fortunately, there's no such thing as an unterminated empty line at the end of a file.)printf
is used instead ofecho
to output the lines becauseecho
doesn't work reliably for arbitrary strings. (For instance, a line containing just-n
would get lost completely byecho "$line"
.) See Why is printf better than echo?.(( idx == 1 )) && printf '%s\n' "${lines[0]}"
) just passes the last line through, after the swapped lines. Other reasonable options would be to drop the last line or print it preceded by an extra blank line. The code can easily be modified to do one of those if desired.