ORS拒绝将输出记录分成新行(ORS refuse to separate output record to new line)
大家好我有这个文件:
paumic@os:~/l26$ cat p1 cat dog cow cat dog mouse dog cow cat所以我想要做的是获得前2列并让它们像这样:
cat dog cat dog dog cow当我使用我的脚本时:
paumic@os:~/l26$ cat skript #!/bin/sh output=$(cat $1 | awk 'BEGIN{ORS="\n"} {print $1, $2}' ) echo $output我得到答案:
paumic@os:~/l26$ ./skript p1 cat dog cat dog dog cow如果我使用别的东西而不是\n它的工作原理。 例:
paumic@os:~/l26$ cat skript #!/bin/sh output=$(cat $1 | awk 'BEGIN{ORS="()"} {print $1, $2}' ) echo $output paumic@os:~/l26$ ./skript p1 cat dog()cat dog()dog cow() paumic@os:~/l26$谢谢你的时间和帮助。
Hello guys i have this file:
paumic@os:~/l26$ cat p1 cat dog cow cat dog mouse dog cow catso what I want to do is to get first 2 columns and have them like this:
cat dog cat dog dog cowwhen i use my script which is:
paumic@os:~/l26$ cat skript #!/bin/sh output=$(cat $1 | awk 'BEGIN{ORS="\n"} {print $1, $2}' ) echo $outputi get answer:
paumic@os:~/l26$ ./skript p1 cat dog cat dog dog cowIf I use something else instead of \n it works. Example:
paumic@os:~/l26$ cat skript #!/bin/sh output=$(cat $1 | awk 'BEGIN{ORS="()"} {print $1, $2}' ) echo $output paumic@os:~/l26$ ./skript p1 cat dog()cat dog()dog cow() paumic@os:~/l26$Thank you for you time and help.
最满意答案
总是引用你的变量。 它可能并不总是需要,但它是一个更安全的习惯。
此外,您可以简化您对awk的使用,并隐式包含对缺少选项的错误处理:
output=$(awk 'BEGIN{ORS="\n"} {print $1 ORS $2}' "${1:?No file provided}" ) echo "$output"虽然明确处理错误可能会更好:
#!/bin/sh if [ -z "$1" ]; then echo "ERROR: no file specified" >&2 exit 1 elif [ ! -f "$1" ]; then echo "ERROR: no such file '$1'" >&2 exit 1 elif [ ! -r "$1" ]; then echo "ERROR: file unreadable: '$1'" >&2 exit 1 elif [ ! -s "$1" ]; then echo "WARNING: file empty: '$1'" >&2 fi output=$(awk -v ORS="\n" '{print $1,$2}' "$1" ) echo "$output"Always quote your variables. It may not always be required, but it's a much safer habit to be in.
Also, you can streamline your use of awk and include error handling for missing options implicitly:
output=$(awk 'BEGIN{ORS="\n"} {print $1 ORS $2}' "${1:?No file provided}" ) echo "$output"Though it would probably be better to be explicit with your error handling:
#!/bin/sh if [ -z "$1" ]; then echo "ERROR: no file specified" >&2 exit 1 elif [ ! -f "$1" ]; then echo "ERROR: no such file '$1'" >&2 exit 1 elif [ ! -r "$1" ]; then echo "ERROR: file unreadable: '$1'" >&2 exit 1 elif [ ! -s "$1" ]; then echo "WARNING: file empty: '$1'" >&2 fi output=$(awk -v ORS="\n" '{print $1,$2}' "$1" ) echo "$output"更多推荐
发布评论