linux - 删除字符串前的空格

标签 linux bash terminal

我想使用管道计算某个文件中字符串的出现次数,而不使用 awk 和 sed 命令。

我的文件内容:

ls -al
bash
cat datoteka.txt
cat d.txt | sort | less
/bin/bash

我使用的终端命令:

 cat $my_file | cut -d ' ' -f 1 | tr '|' '\n' | xargs -r -L1 basename | sort | uniq -c | xargs -r -L1 sh -c 'echo $1 $0'

期望的输出:

bash 2
cat 2
less 1
ls 1
sort 1

In my case, I get:
bash 2
cat 2
ls 1
_sort 1 (not counted )
_less 1 (not counted )

由于这两个字符串前面有空格(我用 _ 标记),因此不计算 Sort 和 less 命令。我应该如何改进我的代码,以删除“sort”和“less”之前的空格?提前致谢!

更新:这是输入文件的第二个更长的示例:

nl /etc/passwd
seq 1 10 | tr "\n" ","
seq 1 10 | tr -d 13579 | tr -s "\n "
seq 1 100 | split -d -a 2 -l10 - blabla-
uname -a | cut -d" " -f1,3
cut -d: -f1 /etc/passwd > fst
cut -d: -f3 /etc/passwd > scnd 
ps -e | column
echo -n ABC | wc -m -c
cmp -s dat1.txt dat1.txt ; echo $?
diff dat1 dat2
ps -e | grep firefox
echo dat1 dat2 dat3 | tr " " "\n" | xargs -I {} -p ln -s {}

最佳答案

如您所知,问题中代码的问题在于 cut 语句。这将 cut 替换为还包含 basename 命令的 shell while 循环:

$ tr '|' '\n' <my_file | while read cmd other; do basename "$cmd"; done | sort | uniq -c | xargs -r -L1 sh -c 'echo $1 $0'
bash 2
cat 2
less 1
ls 1
sort 1

交替排序

以上按命令名称的字母顺序对结果进行排序。相反,如果我们想按出现次数的降序排列,则:

tr '|' '\n' <file2 | while read cmd other; do basename "$cmd"; done | sort | uniq -c | xargs -r -L1 sh -c 'echo $1 $0' | sort -snrk2

将此命令应用于问题中的第二个输入示例:

$ tr '|' '\n' <file2 | while read cmd other; do basename "$cmd"; done | sort | uniq -c | xargs -r -L1 sh -c 'echo $1 $0' | sort -snrk2
tr 4
cut 3
seq 3
echo 2
ps 2
cmp 1
column 1
diff 1
grep 1
nl 1
split 1
uname 1
wc 1
xargs 1

关于linux - 删除字符串前的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29783613/

相关文章:

python - 如何避免在每次导入后重新启动 python shell

linux - 临时更改 $PATH 仅为脚本运行

javascript - 使用 Vue-cli/Webpack 通过一个命令启动客户端和服务器

linux - 删除 linux 文件名的前 3 个字符

在非规范模式中复制和粘贴

linux - PATH变量设置为空,如何修复

linux - airmon-ng找不到任何接口(interface)

linux - 试图运行 xdotool 但得到 'Can' t open display : (null)'

php - 由于依赖问题无法安装 phpmyadmin

c++ - 没有 TTY 的 Exelp 调用 bash