我正在寻找一个简单的控制台解决方案来更改文本文件,如下所示:
//and render it with something like below:
ReactDOM.render(
<ModelCodeLookUpReact />,
document.getElementById('modelCodeLookupContainer_' + id)
);
对于像这样的csv文件:
...
Gender: M
Age: 46
History: 01305
Gender: F
Age: 46
History: 01306
Gender: M
Age: 19
History: 01307
Gender: M
Age: 19
History: 01308
....
任何帮助表示赞赏
通过以下解决方案,我收到了此输出。我做错了吗?
Gender,Age,History
M,46,01305
F,46,01306
M,19,01307
M,19,01308
答案 0 :(得分:1)
这一行应该有所帮助:
awk 'BEGIN{FS=":|\n";RS="Gender";OFS=",";print "Gender,Age,History"}$0{print $2,$4,$6}' file
以您的示例作为输入,它给出:
Gender,Age,History
M, 46, 01305
F, 46, 01306
M, 19, 01307
M, 19, 01308
答案 1 :(得分:1)
这是一种在bash中执行此操作的方法。假设您的数据文件名为data.txt
#!/bin/bash
echo "Gender,Age,History"
while read -r line; do
printf '%s' "$(cut -d ' ' -f2 <<< $line )"
if [[ "$line" =~ ^History.* ]]; then
printf "\n"
else
printf ","
fi
done < data.txt
输出:
Gender,Age,History
M,46,01305
F,46,01306
M,19,01307
M,19,01308
答案 2 :(得分:1)
仅使用bash内置命令,我会说:
#!/bin/bash
echo "Gender,Age,History"
while read line; do
if [[ $line =~ ^Gender:\ *([^\ ]+) ]]; then
r=${BASH_REMATCH[1]}
elif [[ $line =~ ^Age:\ *([^\ ]+) ]]; then
r+=,${BASH_REMATCH[1]}
elif [[ $line =~ ^History:\ *([^\ ]+) ]]; then
echo $r,${BASH_REMATCH[1]}
fi
done < data.text
答案 3 :(得分:0)
我仍然不知道问题究竟在哪里 所以我决定清除所有字符中的数据,除了那些应该存在的字符(很可能是行符号的异常结束)
sed -e 's/[^a-zA-Z*0-9:]/ /g;s/ */ /g' history.txt > output.txt
之后成功使用了@sjsam的解决方案
awk 'BEGIN{printf "Gender,Age,History%s",ORS;FS=":"}{c++} {sub(/^ */,"",$2);printf "%s%s",$2,(c==3)?ORS:","}c==3{c=0}' data.txt >> 1.csv
谢谢大家!