反转文件中的每一行,写入 unix 中的新文件

reverse every other line in a file, write to a new file in unix

假设我有一个文件,wassup.txt其中的行是:

wassup
donut
skateboard
? teeth. !

我想从第二行开始,每隔一行反转字符,然后另存为一个新文件pussaw.txt,其中的行将是:

wassup
tunod
skateboard
! .hteet ?

理想情况下,解决方案将只使用基础 terminal/Unix 函数,或者可能是 awk、perl 或 python。

我知道我可以用代码翻转每一行:

rev wassup.txt > pussaw.txt

问题是如何从第二行开始每隔一行执行一次。

这是一个 awk 解决方案:

awk '
function reverse(s,    r) {
  for (i=length(s); i>0; i--)
    r=r substr (s, i, 1);
  return r
}
{ 
  print ((NR%2) ? [=10=]: reverse([=10=]))
}' file

函数reverse()反转给定的字符串,每隔一行调用一次。

使用 Perl 的选项 assemble 一行代码。

perl -lpe '$_ = reverse $_ unless $.%2' file

-l(小写 L)切断终止换行符并在打印时将其重新添加; -p 使 Perl 遍历输入行并在 运行 脚本之后打印每一行; $_是当前输入行,$.是行号。

简单的Python脚本:

#!/usr/bin/python

import sys

flip = False

for line in sys.stdin:
    if flip:
        print line.strip()
    else:
        print line.strip()[::-1]
    flip = not flip

另存为,例如flip_evens.py,然后将权限 (chmod +x flip_evens.py) 和 运行 修复为 ./flip_evens.py < input.txt

在几乎纯粹的 bash 中,您可以保留一个变量以了解您是在读取偶数行还是奇数行,然后相应地应用 rev

f=0
while IFS= read -r line
do
    (( f%2 )) && rev <<< "$line" || echo "$line"
    (( f++ ))
done < file > new_file

测试

打印到标准输出:

while IFS= read -r line; do (( f%2 )) && rev <<< "$line" || echo "$line"; (( f++ )); done < a
wassup
tunod
skateboard
! .hteet ?

这是 Python 中的另一个解决方案:

>>> text = ['wassup', 'donut', 'skateboard', '? teeth. !']
>>> output = []
>>> for num, line in enumerate(text):
...   if num % 2:  # Starting with the second line (which is an index of `1`...)
...     output.append(''.join(reversed(line)))  # Reverse the string, then join it into a new string.
...   else:
...     output.append(line)
... 
>>> for line in output:
...   print(line)
... 
wassup
tunod
skateboard
! .hteet ?
>>>