How to swap odd and even words in each line?

Ole*_*leg 3 bash string text-processing

I have a bash script that swaps odd and even strings in one file, and saves it to another:

#!/bin/bash

infile="inputfile"
outfile="outputfile"

{
while read -r odd && read -r even
do
    echo "$even"
    echo "$odd"
    unset odd
done < "$infile"

# in case there are an odd number of lines in the file, print the last "odd" line read
if [[ -n $odd ]]; then
    echo "$odd"
fi
} > "$outfile"
Run Code Online (Sandbox Code Playgroud)

How can I swap odd and even words in each line of the file?

Example:

Input file:

one two three four five six
apple banana cocoa dish fish nuts
Run Code Online (Sandbox Code Playgroud)

Output file:

two one four three six five
banana apple dish cocoa nuts fish
Run Code Online (Sandbox Code Playgroud)

jub*_*us1 6

Using Raku (formerly known as Perl_6)

raku -ne 'put .words.rotor(2).map(*.reverse);'  
Run Code Online (Sandbox Code Playgroud)

OR

raku -ne '.words.rotor(2).map(*.reverse).put;'
Run Code Online (Sandbox Code Playgroud)

OR

raku -ne '.words.rotor(2)>>.reverse.put;' 
Run Code Online (Sandbox Code Playgroud)

Sample Input:

one two three four five six
apple banana cocoa dish fish nuts
Run Code Online (Sandbox Code Playgroud)

Sample Output:

two one four three six five
banana apple dish cocoa nuts fish
Run Code Online (Sandbox Code Playgroud)

上面是用 Raku(Perl 编程语言家族的成员)编写的答案。简而言之:使用逐行非自动打印标志raku在命令行调用。-ne当使用-ne-pe命令行标志时,每行都会加载到$_,又名 Raku 的“主题变量”($_也是 Perl 中的“主题变量”)。前导.点是简写形式,$_.表示后面的方法将应用于$_主题变量 。连续的方法与点运算符链接在一起.,每个方法依次转换输入数据。

查看这些方法:我们看到逐行输入在空格上被分解为words,然后一起形成单词对(即提供了rotor参数)。2rotor函数的名称可能有点晦涩,但我猜它意味着数据对象的各个元素被循环或rotor编辑并分组/聚集在一起。在 -ing 之后,使用和应用的函数rotor对每对进行单独寻址。最后,输出打印为.mapreverseput

请注意,上面的代码(使用rotor默认值)将在末尾删除任何“不完整的元素集”。要在最后保留“不完整的元素集”,请更改调用rotor以添加 Truepartial参数,或使用batch这意味着相同的事情:

one two three four five six
apple banana cocoa dish fish nuts
Run Code Online (Sandbox Code Playgroud)

这与以下内容相同:

two one four three six five
banana apple dish cocoa nuts fish
Run Code Online (Sandbox Code Playgroud)

这与以下内容相同:

raku -ne 'put .words.rotor(2, partial => True).map(*.reverse);' 
Run Code Online (Sandbox Code Playgroud)

https://raku.org