如何在 Ubuntu 中使用 bash 反转文件中的所有单词?

Jaf*_*son 1 regex linux bash awk sed

我想反转文件中的完整文本。
假设文件包含:

com.e.h/float
Run Code Online (Sandbox Code Playgroud)

我想得到的输出为:

float/h.e.com 
Run Code Online (Sandbox Code Playgroud)

我已经尝试过命令:

rev file.txt
Run Code Online (Sandbox Code Playgroud)

但我得到了所有反向输出:taolf/h.e.moc 有没有办法获得所需的输出。请告诉我。谢谢。
这是示例文件的链接:示例文本

anu*_*ava 5

您可以使用sedtac

str=$(echo 'com.e.h/float' | sed -E 's/(\W+)/\n\1\n/g' | tac | tr -d '\n')

echo "$str"
float/h.e.com
Run Code Online (Sandbox Code Playgroud)
  • 使用sed我们\n在所有非单词字符之前和之后插入。
  • 使用tac我们反转输出线。
  • 使用tr我们删除所有新行。

如果您有 gnu-awk,那么您可以使用 4 个参数函数调用在单个 awk 命令中完成所有这些操作split,该函数调用分别填充分割字符串和分隔符:

awk '{
   s = ""
   split($0, arr, /\W+/, seps)
   for (i=length(arr); i>=1; i--)
      s = s seps[i] arr[i]
   print s
}' file
Run Code Online (Sandbox Code Playgroud)

对于非 gnu awk,您可以使用:

awk '{
   r = $0
   i = 0
   while (match(r, /[^a-zA-Z0-9_]+/)) {
      a[++i] = substr(r, RSTART, RLENGTH) substr(r, 0, RSTART-1)
      r = substr(r, RSTART+RLENGTH)
   }
   s = r
   for (j=i; j>=1; j--)
      s = s a[j]
   print s
}' file
Run Code Online (Sandbox Code Playgroud)