首页 > 解决方案 > 从 CSV 文件中提取两列,将它们拆分为 while read 循环并对每个字符串执行不同的命令

问题描述

首先我必须承认,我是 bash 的菜鸟,如果我犯了任何愚蠢的错误,我很抱歉。我搜索了很多,但我认为我缺少基础知识。

我想做的事:

编辑:这是示例数据:

column1;column2;column3-iwant;column4;column5 is what i want;;;
loerm ipsum; dolor sit ame;filename;consetur;the content i want in the file;;;
justo;labore;myfilename2;labore;;sometimes something here;

我的第一次尝试很有希望:

cut -d\; -f3,5 myFile.csv | while read line; do echo $line; done

我得到以下输出:

filename1; Value1, Value2, Value3
filename2, Value B, ValueC, ValueD

我现在想做的是用“;”分割这个字符串 作为分隔符并创建一个文件“filename1.txt”并将内容“Value1,Value2,Value3”放入该文件中。

我尝试了下一步如下

cut -d\; -f3,5 myFile.csv | while read line; do filname=$(echo "$line" | cut -d\; -f1) | echo $filename; done

这为每个循环打印 $line

下一个赌注:

cut -d\; -f3,5 myfile.csv | while read line; do filename=`echo $line | cut -d\; -f1` | mycontent=`echo $line | cut -d\; -f2` | echo "$filename"; done

非常接近,但它会为每个循环打印 csv 文件的最后一行。

我的错误是什么?干杯大卫

标签: bashcut

解决方案


大卫!

我也是这里的新手,但我想我有答案。

如果您使用此内容创建一个脚本文件并使其可执行,然后您可以键入 ./script.bash NameOfMyFile.csv,它会完成您的任务。您至少可以将此代码用作开始的地方。祝你好运!

#!/bin/bash
file=$1
while IFS=';' read -r newfile contents 
do
   echo "Create file: $newfile  ==> with contents: $contents"
   echo $contents > $newfile
done < "$file"

我提供给它的示例文件如下所示:

Name1; Put this stuff in the first place I want it And then put in more stuff
Name2; I might, have some; puncuated stuff! But it shouldn't matter.
Name3; 20394)@(#$
Name4; No newline at the end of this line

输出:

Create file: Name1  ==> with contents:  Put this stuff in the first place I want it And then put in more stuff
Create file: Name2  ==> with contents:  I might, have some; puncuated stuff! But it shouldn't matter.
Create file: Name3  ==> with contents:  20394)@(#$
Create file: Name4  ==> with contents:  No newline at the end of this line

我希望这有帮助!凯莉


推荐阅读