简体   繁体   English

需要帮助从bash脚本中的awk引用转义

[英]Need help escaping from awk quotations in bash script

I have an alias in my bashrc file that outputs current folder contents and system available storage, updated continuously by the watch function. 我的bashrc文件中有一个别名,该别名输出当前文件夹内容和系统可用存储空间,并由监视功能连续更新。

alias wtch='watch -n 0 -t "du -sch * -B 1000000 2>/dev/null | sort -h && df -h -B 1000000| head -2 | awk '{print \$4}'"'

The string worked fine until I put in the awk part. 在我放入awk部分之前,字符串工作正常。 I know I need to escape the single quotation marks, while still staying in the double quotation marks and the $4 but I haven't been able to get it to work. 我知道我需要转义使用单引号,同时仍然保持在双引号和$ 4中,但我无法使其正常工作。 What am I doing wrong? 我究竟做错了什么?

This is the error I get 这是我得到的错误

-bash: alias: $4}": not found

Since the quoting for the alias is making it tough, you could just make it a function instead: 由于别名的引用使它变得很难,因此可以将其改为一个函数:

wtch() {
    watch -n 0 -t "du -sch * -B 1000000 2>/dev/null | sort -h && df -h -B 1000000| head -2 | awk '{print $4}'"
}

This is a lot like issue 2 in the BashFAQ/050 这很像BashFAQ / 050中的问题2

Also, a minor thing but you can skip the head process at the end and just have awk do it, even exiting after the second row like 另外,这是一件很小的事情,但是您可以在最后跳过head过程,而只需执行awk ,甚至可以在第二行之后退出,例如

wtch() {
    watch -n 0 -t "du -sch * -B 1000000 2>/dev/null | sort -h && df -h -B 1000000| awk '{print $4} NR >= 3 {exit}'"
}

In this case you can use cut instead of awk . 在这种情况下,可以使用cut代替awk And you'll have the same effect. 而且您将获得相同的效果。

alias wtch="watch -n 0 -t 'du -sch * -B 1000000 2>/dev/null | sort -h && df -h -B 1000000| head -2 | cut -d\  -f4'"

Explaining cut : 解释cut

-d option defines a delimiter
-d\  means that my delimiter is space
-f selects a column
-f4 gives you the fourth column

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM