Changing second column in csv conditionally The 2019 Stack Overflow Developer Survey Results Are InHelp using Awk to change a fileSearch csv file columnPrinting pattern of “C” characterHow can I count lines of differently named files, and write the outcome to a csv file?Create csv from inconsistent text fileSum column 2 of .csv file if column 1 is the sameSearching for data from file1 in file2view the column names for CSV file?Delete multiple rows in csv fileMove specific column from csv file in front (select column by name)

Is it possible to force a package to be called last in the entirety of the LaTeX, when called in the class file?

Can someone be penalized for an "unlawful" act if no penalty is specified?

Why isn't the circumferential light around the M87 black hole's event horizon symmetric?

Output the Arecibo Message

Identify This Plant (Flower)

What tool would a Roman-age civilization have for the breaking of silver and other metals into dust?

What does ひと匙 mean in this manga and has it been used colloquially?

What is the closest word meaning "respect for time / mindful"

Why is my custom API endpoint not working?

Is there any way to tell whether the shot is going to hit you or not?

Why isn't airport relocation done gradually?

Is bread bad for ducks?

Why do UK politicians seemingly ignore opinion polls on Brexit?

Are there incongruent pythagorean triangles with the same perimeter and same area?

Why can Shazam fly?

What is the motivation for a law requiring 2 parties to consent for recording a conversation

Can we generate random numbers using irrational numbers like π and e?

What is the meaning of Triage in Cybersec world?

The difference between dialogue marks

Origin of "cooter" meaning "vagina"

Are children permitted to help build the Beis Hamikdash?

Should I use my personal e-mail address, or my workplace one, when registering to external websites for work purposes?

Falsification in Math vs Science

What did it mean to "align" a radio?



Changing second column in csv conditionally



The 2019 Stack Overflow Developer Survey Results Are InHelp using Awk to change a fileSearch csv file columnPrinting pattern of “C” characterHow can I count lines of differently named files, and write the outcome to a csv file?Create csv from inconsistent text fileSum column 2 of .csv file if column 1 is the sameSearching for data from file1 in file2view the column names for CSV file?Delete multiple rows in csv fileMove specific column from csv file in front (select column by name)



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








5















I have a csv file that looks like:



data/train/4/36280.png,four
data/train/2/10317.png,two
data/train/2/57890.png,two
data/train/1/53448.png,one
data/train/8/58233.png,eight
data/train/4/23599.png,four
data/train/2/35051.png,two
data/train/1/12323.png,one
data/train/9/18562.png,nine
data/train/8/46629.png,eight
data/train/7/1746.png,seven


Where first column is path and second is class. I would like to change the second column conditionally. In pseudo code I want something like:



If second column "four" change it to the next row's class


So far I've tried just to see if I can change ne class to another, but without success:



awk ' if ($2 == "zero") $2="one"; print $0 ' train.csv > new_file.csv


gives me the same csv.



Basically I would like a script that gives me following output csv:



data/train/4/36280.png,seven
data/train/2/10317.png,four
data/train/2/57890.png,two
data/train/1/53448.png,two
data/train/8/58233.png,one
data/train/4/23599.png,eight
data/train/2/35051.png,four
data/train/1/12323.png,two
data/train/9/18562.png,one
data/train/8/46629.png,nine
data/train/7/1746.png,eight









share|improve this question









New contributor




iKnowItAll is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • The default field separator in awk is whitespace; if you have comma separated data, you will need to set the separator accordingly - either with the -F command line option, or by setting FS="," in a BEGIN rule.

    – steeldriver
    Apr 5 at 7:00











  • What is "the next rows class" ? Could you please edit your question and add an example output?

    – RoVo
    Apr 5 at 7:17











  • You mean like `awk FS="," ' if ($2 == "zero") $2="one"; print $0 ' train.csv > new_file.csv´ Next row class for line 1 is line 2, column 2. I basically want to shuffle the class in an easy way

    – iKnowItAll
    Apr 5 at 7:24

















5















I have a csv file that looks like:



data/train/4/36280.png,four
data/train/2/10317.png,two
data/train/2/57890.png,two
data/train/1/53448.png,one
data/train/8/58233.png,eight
data/train/4/23599.png,four
data/train/2/35051.png,two
data/train/1/12323.png,one
data/train/9/18562.png,nine
data/train/8/46629.png,eight
data/train/7/1746.png,seven


Where first column is path and second is class. I would like to change the second column conditionally. In pseudo code I want something like:



If second column "four" change it to the next row's class


So far I've tried just to see if I can change ne class to another, but without success:



awk ' if ($2 == "zero") $2="one"; print $0 ' train.csv > new_file.csv


gives me the same csv.



Basically I would like a script that gives me following output csv:



data/train/4/36280.png,seven
data/train/2/10317.png,four
data/train/2/57890.png,two
data/train/1/53448.png,two
data/train/8/58233.png,one
data/train/4/23599.png,eight
data/train/2/35051.png,four
data/train/1/12323.png,two
data/train/9/18562.png,one
data/train/8/46629.png,nine
data/train/7/1746.png,eight









share|improve this question









New contributor




iKnowItAll is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • The default field separator in awk is whitespace; if you have comma separated data, you will need to set the separator accordingly - either with the -F command line option, or by setting FS="," in a BEGIN rule.

    – steeldriver
    Apr 5 at 7:00











  • What is "the next rows class" ? Could you please edit your question and add an example output?

    – RoVo
    Apr 5 at 7:17











  • You mean like `awk FS="," ' if ($2 == "zero") $2="one"; print $0 ' train.csv > new_file.csv´ Next row class for line 1 is line 2, column 2. I basically want to shuffle the class in an easy way

    – iKnowItAll
    Apr 5 at 7:24













5












5








5








I have a csv file that looks like:



data/train/4/36280.png,four
data/train/2/10317.png,two
data/train/2/57890.png,two
data/train/1/53448.png,one
data/train/8/58233.png,eight
data/train/4/23599.png,four
data/train/2/35051.png,two
data/train/1/12323.png,one
data/train/9/18562.png,nine
data/train/8/46629.png,eight
data/train/7/1746.png,seven


Where first column is path and second is class. I would like to change the second column conditionally. In pseudo code I want something like:



If second column "four" change it to the next row's class


So far I've tried just to see if I can change ne class to another, but without success:



awk ' if ($2 == "zero") $2="one"; print $0 ' train.csv > new_file.csv


gives me the same csv.



Basically I would like a script that gives me following output csv:



data/train/4/36280.png,seven
data/train/2/10317.png,four
data/train/2/57890.png,two
data/train/1/53448.png,two
data/train/8/58233.png,one
data/train/4/23599.png,eight
data/train/2/35051.png,four
data/train/1/12323.png,two
data/train/9/18562.png,one
data/train/8/46629.png,nine
data/train/7/1746.png,eight









share|improve this question









New contributor




iKnowItAll is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












I have a csv file that looks like:



data/train/4/36280.png,four
data/train/2/10317.png,two
data/train/2/57890.png,two
data/train/1/53448.png,one
data/train/8/58233.png,eight
data/train/4/23599.png,four
data/train/2/35051.png,two
data/train/1/12323.png,one
data/train/9/18562.png,nine
data/train/8/46629.png,eight
data/train/7/1746.png,seven


Where first column is path and second is class. I would like to change the second column conditionally. In pseudo code I want something like:



If second column "four" change it to the next row's class


So far I've tried just to see if I can change ne class to another, but without success:



awk ' if ($2 == "zero") $2="one"; print $0 ' train.csv > new_file.csv


gives me the same csv.



Basically I would like a script that gives me following output csv:



data/train/4/36280.png,seven
data/train/2/10317.png,four
data/train/2/57890.png,two
data/train/1/53448.png,two
data/train/8/58233.png,one
data/train/4/23599.png,eight
data/train/2/35051.png,four
data/train/1/12323.png,two
data/train/9/18562.png,one
data/train/8/46629.png,nine
data/train/7/1746.png,eight






command-line text-processing awk csv






share|improve this question









New contributor




iKnowItAll is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




iKnowItAll is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Apr 6 at 7:13









Zanna

51.3k13140243




51.3k13140243






New contributor




iKnowItAll is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Apr 5 at 6:55









iKnowItAlliKnowItAll

283




283




New contributor




iKnowItAll is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





iKnowItAll is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






iKnowItAll is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • The default field separator in awk is whitespace; if you have comma separated data, you will need to set the separator accordingly - either with the -F command line option, or by setting FS="," in a BEGIN rule.

    – steeldriver
    Apr 5 at 7:00











  • What is "the next rows class" ? Could you please edit your question and add an example output?

    – RoVo
    Apr 5 at 7:17











  • You mean like `awk FS="," ' if ($2 == "zero") $2="one"; print $0 ' train.csv > new_file.csv´ Next row class for line 1 is line 2, column 2. I basically want to shuffle the class in an easy way

    – iKnowItAll
    Apr 5 at 7:24

















  • The default field separator in awk is whitespace; if you have comma separated data, you will need to set the separator accordingly - either with the -F command line option, or by setting FS="," in a BEGIN rule.

    – steeldriver
    Apr 5 at 7:00











  • What is "the next rows class" ? Could you please edit your question and add an example output?

    – RoVo
    Apr 5 at 7:17











  • You mean like `awk FS="," ' if ($2 == "zero") $2="one"; print $0 ' train.csv > new_file.csv´ Next row class for line 1 is line 2, column 2. I basically want to shuffle the class in an easy way

    – iKnowItAll
    Apr 5 at 7:24
















The default field separator in awk is whitespace; if you have comma separated data, you will need to set the separator accordingly - either with the -F command line option, or by setting FS="," in a BEGIN rule.

– steeldriver
Apr 5 at 7:00





The default field separator in awk is whitespace; if you have comma separated data, you will need to set the separator accordingly - either with the -F command line option, or by setting FS="," in a BEGIN rule.

– steeldriver
Apr 5 at 7:00













What is "the next rows class" ? Could you please edit your question and add an example output?

– RoVo
Apr 5 at 7:17





What is "the next rows class" ? Could you please edit your question and add an example output?

– RoVo
Apr 5 at 7:17













You mean like `awk FS="," ' if ($2 == "zero") $2="one"; print $0 ' train.csv > new_file.csv´ Next row class for line 1 is line 2, column 2. I basically want to shuffle the class in an easy way

– iKnowItAll
Apr 5 at 7:24





You mean like `awk FS="," ' if ($2 == "zero") $2="one"; print $0 ' train.csv > new_file.csv´ Next row class for line 1 is line 2, column 2. I basically want to shuffle the class in an easy way

– iKnowItAll
Apr 5 at 7:24










1 Answer
1






active

oldest

votes


















6














bash solution:



readarray -t filename < <(cut -d ',' -f1 train.csv)
readarray -t class < <(cut -d ',' -f2 train.csv)

for (( i=0; i<$#filename[@]; i++ )); do
printf '%s,%sn' "$filename[$i]" "$class[$((i-1))]";
done > new_file.csv



Equivalent awk solution:



awk -F, '

filename[NR]=$1
class[NR]=$2

END
OFS=","
print filename[1],class[NR]
for (i=2;i<=NR;i++)
print filename[i],class[i-1]


' train.csv > new_file.csv


Both solutions first read the lines into arrays filename and class. Only difference is that the bash array starts with 0, the awk array with 1.



Then, we loop over the arrays and print the desired output. In the awk solution, we need to treat the first line separately as, unlike in bash, array[-1] does not return the last element.



The awk solution is a bit faster.






share|improve this answer

























  • I tried it and it looks great! Could I ask how I would save this to a new CSV? I guess its putting > new_file.csv at the end maybe?

    – iKnowItAll
    Apr 5 at 7:43











  • exactly, added to the answer

    – RoVo
    Apr 5 at 7:44











  • Thanks alot!! Works great!

    – iKnowItAll
    Apr 5 at 7:45











  • Excellent answer, I could not think of any other way then first loading the csv into a RDMS like PostgreSQL

    – Letholdrus
    9 hours ago











Your Answer








StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "89"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);






iKnowItAll is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f1131364%2fchanging-second-column-in-csv-conditionally%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









6














bash solution:



readarray -t filename < <(cut -d ',' -f1 train.csv)
readarray -t class < <(cut -d ',' -f2 train.csv)

for (( i=0; i<$#filename[@]; i++ )); do
printf '%s,%sn' "$filename[$i]" "$class[$((i-1))]";
done > new_file.csv



Equivalent awk solution:



awk -F, '

filename[NR]=$1
class[NR]=$2

END
OFS=","
print filename[1],class[NR]
for (i=2;i<=NR;i++)
print filename[i],class[i-1]


' train.csv > new_file.csv


Both solutions first read the lines into arrays filename and class. Only difference is that the bash array starts with 0, the awk array with 1.



Then, we loop over the arrays and print the desired output. In the awk solution, we need to treat the first line separately as, unlike in bash, array[-1] does not return the last element.



The awk solution is a bit faster.






share|improve this answer

























  • I tried it and it looks great! Could I ask how I would save this to a new CSV? I guess its putting > new_file.csv at the end maybe?

    – iKnowItAll
    Apr 5 at 7:43











  • exactly, added to the answer

    – RoVo
    Apr 5 at 7:44











  • Thanks alot!! Works great!

    – iKnowItAll
    Apr 5 at 7:45











  • Excellent answer, I could not think of any other way then first loading the csv into a RDMS like PostgreSQL

    – Letholdrus
    9 hours ago















6














bash solution:



readarray -t filename < <(cut -d ',' -f1 train.csv)
readarray -t class < <(cut -d ',' -f2 train.csv)

for (( i=0; i<$#filename[@]; i++ )); do
printf '%s,%sn' "$filename[$i]" "$class[$((i-1))]";
done > new_file.csv



Equivalent awk solution:



awk -F, '

filename[NR]=$1
class[NR]=$2

END
OFS=","
print filename[1],class[NR]
for (i=2;i<=NR;i++)
print filename[i],class[i-1]


' train.csv > new_file.csv


Both solutions first read the lines into arrays filename and class. Only difference is that the bash array starts with 0, the awk array with 1.



Then, we loop over the arrays and print the desired output. In the awk solution, we need to treat the first line separately as, unlike in bash, array[-1] does not return the last element.



The awk solution is a bit faster.






share|improve this answer

























  • I tried it and it looks great! Could I ask how I would save this to a new CSV? I guess its putting > new_file.csv at the end maybe?

    – iKnowItAll
    Apr 5 at 7:43











  • exactly, added to the answer

    – RoVo
    Apr 5 at 7:44











  • Thanks alot!! Works great!

    – iKnowItAll
    Apr 5 at 7:45











  • Excellent answer, I could not think of any other way then first loading the csv into a RDMS like PostgreSQL

    – Letholdrus
    9 hours ago













6












6








6







bash solution:



readarray -t filename < <(cut -d ',' -f1 train.csv)
readarray -t class < <(cut -d ',' -f2 train.csv)

for (( i=0; i<$#filename[@]; i++ )); do
printf '%s,%sn' "$filename[$i]" "$class[$((i-1))]";
done > new_file.csv



Equivalent awk solution:



awk -F, '

filename[NR]=$1
class[NR]=$2

END
OFS=","
print filename[1],class[NR]
for (i=2;i<=NR;i++)
print filename[i],class[i-1]


' train.csv > new_file.csv


Both solutions first read the lines into arrays filename and class. Only difference is that the bash array starts with 0, the awk array with 1.



Then, we loop over the arrays and print the desired output. In the awk solution, we need to treat the first line separately as, unlike in bash, array[-1] does not return the last element.



The awk solution is a bit faster.






share|improve this answer















bash solution:



readarray -t filename < <(cut -d ',' -f1 train.csv)
readarray -t class < <(cut -d ',' -f2 train.csv)

for (( i=0; i<$#filename[@]; i++ )); do
printf '%s,%sn' "$filename[$i]" "$class[$((i-1))]";
done > new_file.csv



Equivalent awk solution:



awk -F, '

filename[NR]=$1
class[NR]=$2

END
OFS=","
print filename[1],class[NR]
for (i=2;i<=NR;i++)
print filename[i],class[i-1]


' train.csv > new_file.csv


Both solutions first read the lines into arrays filename and class. Only difference is that the bash array starts with 0, the awk array with 1.



Then, we loop over the arrays and print the desired output. In the awk solution, we need to treat the first line separately as, unlike in bash, array[-1] does not return the last element.



The awk solution is a bit faster.







share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 5 at 8:09

























answered Apr 5 at 7:39









RoVoRoVo

8,1901943




8,1901943












  • I tried it and it looks great! Could I ask how I would save this to a new CSV? I guess its putting > new_file.csv at the end maybe?

    – iKnowItAll
    Apr 5 at 7:43











  • exactly, added to the answer

    – RoVo
    Apr 5 at 7:44











  • Thanks alot!! Works great!

    – iKnowItAll
    Apr 5 at 7:45











  • Excellent answer, I could not think of any other way then first loading the csv into a RDMS like PostgreSQL

    – Letholdrus
    9 hours ago

















  • I tried it and it looks great! Could I ask how I would save this to a new CSV? I guess its putting > new_file.csv at the end maybe?

    – iKnowItAll
    Apr 5 at 7:43











  • exactly, added to the answer

    – RoVo
    Apr 5 at 7:44











  • Thanks alot!! Works great!

    – iKnowItAll
    Apr 5 at 7:45











  • Excellent answer, I could not think of any other way then first loading the csv into a RDMS like PostgreSQL

    – Letholdrus
    9 hours ago
















I tried it and it looks great! Could I ask how I would save this to a new CSV? I guess its putting > new_file.csv at the end maybe?

– iKnowItAll
Apr 5 at 7:43





I tried it and it looks great! Could I ask how I would save this to a new CSV? I guess its putting > new_file.csv at the end maybe?

– iKnowItAll
Apr 5 at 7:43













exactly, added to the answer

– RoVo
Apr 5 at 7:44





exactly, added to the answer

– RoVo
Apr 5 at 7:44













Thanks alot!! Works great!

– iKnowItAll
Apr 5 at 7:45





Thanks alot!! Works great!

– iKnowItAll
Apr 5 at 7:45













Excellent answer, I could not think of any other way then first loading the csv into a RDMS like PostgreSQL

– Letholdrus
9 hours ago





Excellent answer, I could not think of any other way then first loading the csv into a RDMS like PostgreSQL

– Letholdrus
9 hours ago










iKnowItAll is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















iKnowItAll is a new contributor. Be nice, and check out our Code of Conduct.












iKnowItAll is a new contributor. Be nice, and check out our Code of Conduct.











iKnowItAll is a new contributor. Be nice, and check out our Code of Conduct.














Thanks for contributing an answer to Ask Ubuntu!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f1131364%2fchanging-second-column-in-csv-conditionally%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Export of reprojected layer from GEE fails Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Iterate over features and years to export images for each feature-yearEarth engine reproject: why does reprojecting a pixel at 30m scale gives me pixels with an area of ~550?Exporting slope raster for entire country in GEEGEE Landsat SR year composite // mask cloud / shadow out w/ other method than quality pixel"export region contains no valid (un-masked) pixels - Google Earth EgineGoogle Earth Engine, how to distinguish between rivers/streams and ponds/lakes in a water maskPython script tool fails when processing rainfall data from Google Earth EngineGoogle Earth Engine Error: Number of pixels requested from Image.load exceeds the maximum allowedCloudfree images in small area from Sentinel-2Using Image exportToDrive in Google Earth Engine?

Crop image to path created in TikZ? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Crop an inserted image?TikZ pictures does not appear in posterImage behind and beyond crop marks?Tikz picture as large as possible on A4 PageTransparency vs image compression dilemmaHow to crop background from image automatically?Image does not cropTikzexternal capturing crop marks when externalizing pgfplots?How to include image path that contains a dollar signCrop image with left size given

Creating closest line along the point''s azimuth using PostgreSQL Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Drawing line between points at specific distance in PostGIS?How to efficiently find the closest point over the dateline?How to find the nearest point by using PostGIS function?PostGIS nearest point with LATERAL JOIN in PostgreSQL 9.3+Creating a table and inserting selected streets using plpgsql functionsCreating a table that stores Distances and other columnSaving select query results (year wise) from PostgreSQL/PostGIS to text filesWhat is the information behind this geometry?How to give start and end vertex ids dynamically in pgr_dijkstra?Point to Polygon nearest distance DS_distance is not using geography index & knn <-> or <#> does not give result in orderLine to point conversion with start point and end point detection?