2017-04-20 71 views
0

我困在此刻,需要一些帮助。我运行下面的命令:Bash输出到文件没有新行

echo $(ps aux |sort -nrk 3,3 | head -n 10) > text.txt 

而且我得到的输出都在一个大的块

student 2066 16.5 7.4 1609208 299500 ? Ssl 07:31 12:16 compiz student 2803 13.3 8.3 2261736 339840 ? Sl 07:33 9:40 /usr/lib/firefox/plugin-container -greomni /usr/lib/firefox/omni.ja -appomni /usr/lib/firefox/browser/omni.ja -appdir /usr/lib/firefox/browser 2720 true tab student 2720 6.5 9.1 2435552 370424 ? Sl 07:33 4:47 /usr/lib/firefox/firefox root 884 5.3 2.8 365268 116248 tty7 Ssl+ 07:31 4:02 /usr/lib/xorg/Xorg -core :0 -seat seat0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch student 2700 0.6 1.1 801556 46540 ? Sl 07:33 0:26 /usr/bin/gedit --gapplication-service student 2023 0.1 3.4 1312876 138932 ? Sl 07:31 0:05 /usr/bin/gnome-software --gapplication-service student 2017 0.1 1.3 832524 55068 ? Sl 07:31 0:04 nautilus -n student 1337 0.1 0.0 116164 2084 ? Sl 07:31 0:07 /usr/bin/VBoxClient --draganddrop whoopsie 592 0.0 0.3 373952 12352 ? Ssl 07:30 0:00 /usr/bin/whoopsie -f USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND 

我想知道是否有离开具有行输出线。

student 2066 16.5 7.4 1609208 299500 ? Ssl 07:31 12:16 compiz 
student 2803 13.3 8.3 2261736 339840 ? Sl 07:33 9:40 /usr/lib/firefox/plugin-container -greomni /usr/lib/firefox/omni.ja -appomni /usr/lib/firefox/browser/omni.ja -appdir /usr/lib/firefox/browser 2720 true tab 
student 2720 6.5 9.1 2435552 370424 ? Sl 07:33 4:47 /usr/lib/firefox/firefox root 884 5.3 2.8 365268 116248 tty7 Ssl+ 07:31 4:02 /usr/lib/xorg/Xorg -core :0 -seat seat0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch student 2700 0.6 1.1 801556 46540 ? Sl 07:33 0:26 /usr/bin/gedit --gapplication-service student 2023 0.1 3.4 1312876 138932 ? Sl 07:31 0:05 /usr/bin/gnome-software --gapplication-service student 2017 0.1 1.3 832524 55068 ? Sl 07:31 0:04 nautilus -n 
student 1337 0.1 0.0 116164 2084 ? Sl 07:31 0:07 /usr/bin/VBoxClient --draganddrop whoopsie 592 0.0 0.3 373952 12352 ? Ssl 07:30 0:00 /usr/bin/whoopsie -f USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND 

我希望做它在BASH只是因为这是我此刻的自学和任何帮助,将不胜感激。

+2

只是'ps aux | sort -nrk 3,3 | head -n 10> text.txt' – hek2mgl

+0

@Matthew Swart我真的很想知道为什么你使用echo $(某些命令)而不是直接使用它们/ –

回答

1
somecmd $(...) 

这是最常见的错误在猛砸/ POSIX shell脚本,使,不引用变量的扩展或命令替换。

的问题是相同的,如下:

var="foo  bar"    # couple of spaces 
echo $var      

由于$var不是引用,它的分裂上的空白,并将得到的词作为独立参数来echo。并且echo输出由单个空格分隔的所有参数。在你的例子中,来自命令替换的换行符同样用于分割输入。

比较

echo "$var" 

看到:http://mywiki.wooledge.org/WordSplittinghttp://mywiki.wooledge.org/BashPitfalls


当然,前两个项目,什么命令替换$(...)确实是采取了命令的输出和把它放在另一个命令的命令行上。这与echo的做法相反,它从命令行输入并将其打印到标准输出。所以你可以直接删除并重定向你的ps ...命令的输出。

1

你为什么要echo命令替换($(..))输出,当你可以做,

ps aux |sort -nrk 3,3 | head -n 10 > text.txt 
+0

就像我在过去一周从所有阅读过的东西中学到的一样线上。 –