bash 将每个字符放在一个新行上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9899049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Placing every character on a new line
提问by Village
I have a file like this:
我有一个这样的文件:
This is a sentence.
This is another sentence.
I need to put a new line after each character, such that only one character appears on every line, e.g.:
我需要在每个字符后放置一个新行,这样每一行只出现一个字符,例如:
T
h
i
s
i
s
a
s
e
n
t
e
n
c
e
.
T
h
i
s
i
s
a
n
o
t
h
e
r
s
e
n
t
e
n
c
e
.
- The file is in UTF-8 and contains many non-English characters.
- It does not matter if spaces or carriage returns have their own line.
- 该文件采用 UTF-8 格式并包含许多非英文字符。
- 空格或回车是否有自己的行并不重要。
How can I remove every character to a new line?
如何将每个字符删除到新行?
采纳答案by Paul
Using sed replace every character with itself followed by a newline:
使用 sed 将每个字符替换为它自己,后跟一个换行符:
sed 's/./$ grep -o . file
$ echo This is a sentence. | grep -o .
\n/g' -i filename
回答by Lri
sed $'s/./&\\\n/g'(with BSD sed)- Or
sed 's/./&\n/g'with GNU sed - Doesn't include empty lines for linefeeds
- Or
fold -w1-wspecifies width in characters- Doesn't include empty lines for linefeeds
while IFS= read -r -n1 -d '' c; do printf %s\\n "$c"; done- Includes empty lines for linefeeds with
-d '' - The only option for
readspecified by POSIX is-r
- Includes empty lines for linefeeds with
gawk -F '' 'OFS="\n"{$1=$1}1'- Or
awk 'BEGIN{FS="";OFS="\n"}{$1=$1}1'in nawk (BSD awk, the awk that comes with OS X); it doesn't work with multibyte characters though - Neither includes empty lines for linefeeds
- Or
sed $'s/./&\\\n/g'(使用 BSD sed)- 或者
sed 's/./&\n/g'使用 GNU sed - 不包括换行符的空行
- 或者
fold -w1-w以字符为单位指定宽度- 不包括换行符的空行
while IFS= read -r -n1 -d '' c; do printf %s\\n "$c"; done- 包括换行符的空行
-d '' readPOSIX 指定的唯一选项是-r
- 包括换行符的空行
gawk -F '' 'OFS="\n"{$1=$1}1'- 或者
awk 'BEGIN{FS="";OFS="\n"}{$1=$1}1'在nawk(BSD awk,OS X自带的awk);虽然它不适用于多字节字符 - 都不包括换行符的空行
- 或者
All except the nawk command worked with non-ASCII characters in my environment when LC_CTYPEwas set to a UTF-8 locale. None collapsed or stripped spaces.
当LC_CTYPE设置为 UTF-8 语言环境时,除 nawk 命令之外的所有命令都在我的环境中使用非 ASCII 字符。没有折叠或剥离的空间。
回答by kenorb
Use grep, in example:
使用grep, 例如:
$ fold -w1 file
$ echo This is a sentence. | fold -w1
or fold:
或fold:
awk -F '' -v 'OFS=\n' '{=}1' filename
回答by glenn Hymanman
Using awk's input and output field separators:
使用 awk 的输入和输出字段分隔符:
perl -F// -lane 'print join "\n", @F' filename
or Perl
或 Perl
while read -r -n 1 -d '' -u 9
do
printf "Uppercase '${REPLY^^}', "
printf "lowercase '${REPLY,,}', "
printf "literal $(printf "$REPLY" | uniname -bcegpu | tail -1)"
printf '\n'
done 9< "path"
回答by l0b0
Not as short as PaulP.R.O.'s answer, but useful if you want to do some operation on each character:
不像PaulP.RO 的回答那么简短,但如果您想对每个字符进行一些操作,则很有用:
##代码##
