Print bash array of arrays to certain format - linux

I have a bash array as follows:
fruits=(
F001 "Sour fruit" 5
F002 "Sweet fruit" 15
F003 "Good fruit" 10
)
I want to access this array and print it as follows:
Fruit code: F001, Desc: Sour fruit, Price: 5
Fruit code: F002, Desc: Sweet fruit, Price: 15
Fruit code: F003, Desc: Good fruit, Price: 10
I tried the following code, But it's giving me a wrong output
for f in "${fruits[#]}"; do
IFS=" " read -r -a arr <<<"${f}"
code="${arr[0]}"
desc="${arr[1]}"
price="${arr[2]}"
echo "Fruit code: : ${code}, Desc: ${desc}, Price: ${price}"
echo
done
Anyine know how to do this :)

The bash array you define does not have 3 elements, but 9. So you can quickly do this with a modulo 3 operation:
for ((i=0;i<"${#fruits[#]}";i=i+3)); do
code="${fruits[i]}"
desc="${fruits[i+1]}"
price="${fruits[i+2]}"
echo "Fruit code: : ${code}, Desc: ${desc}, Price: ${price}"
done

Related

Create a string with an offset

I would like to create a String where the values have a fixed offset where to add values to a string.
Example
ID(0) Name(10) Lastname(20) City(30)
example
1 Chris Smith Paris
I have found
StringBuffer.putAt(IntRange range, Object value)
or similiar, but I don't want to have a range, but an index where to start.
StringBufferWriter.write(String text, int offset, int length)
I have found [StrindBufferWriter][1], but not sure if the package codehause is an offical package I can use.
Any suggestions what to use here?
You can use String.padRight to achieve this effect:
def users = [
[id: 1, name: 'Chris', lastname: 'Smith', city:'Paris'],
[id: 2, name: 'Tim', lastname: 'Yates', city:'Manchester'],
]
users.each { user ->
println "${user.id.toString().padRight(10)}${user.name.padRight(10)}${user.lastname.padRight(20)}$user.city"
}
Which prints:
1 Chris Smith Paris
2 Tim Yates Manchester

Searching a JSON with NODEJS

i have been trying to implement a search bar. My idea is that the user can partially type the word and then i can pass the variable in the response so it is used in my EJS. I am not using SQL databases on purpose, as im trying to keep this site running only with JSON file as database. I have tried but cant seem to make it work. I have tried many ways.
let userSearch = (req.body.search)
let allProducts = data
let filteredProducts = allProducts.filter(x => x.title == x.title.indexOf(userSearch))
console.log(allProducts), gives you this :
[
{
id: 1,
title: 'Chicken and vegetables stir-fry',
Ingredients: [
'2 tbsp peanut oil',
'3 Lilydale Free Range Chicken Breast, trimmed, cut across the grain into thin strips',
'1 brown onion, cut into thin wedges',
'1 red capsicum, deseeded, cut into thin strips',
'250g button mushrooms or mushroom caps, sliced',
'1 bunch broccolini, cut into 4cm lengths',
'2cm piece fresh ginger, peeled, finely grated or chopped',
'2 garlic cloves, finely chopped',
'2 fresh birdseye chillies, deseeded if desired, thinly sliced',
'2 tbsp salt-reduced soy sauce',
'1 1/2 tbsp oyster sauce',
'1 tbsp water',
'100g bean sprouts, to serve',
'Coriander leaves, to serve',
'Cooked white rice or noodles, to serve'
],
description: 'Delicious and nutricious',
image: 'chickenAndVeggies.jpeg',
belongsTo: 'maria#hotmail.com'
},
{
id: 2,
title: 'Chocolate fudge cake',
Ingredients: [
'2 150ml sunflower oil, plus extra for the tin',
'175g self-raising flour',
'2 tbsp cocoa powder',
'1 tsp bicarbonate of soda',
'150g caster sugar',
'2 tbsp golden syrup',
'2 large eggs, lightly beaten',
'150ml semi-skimmed milk'
],
description: 'What´s better than a choco cake?',
image: 'chococake.jpeg',
belongsTo: 'maria#hotmail.com'
},
{
id: 3,
title: 'Quiche Lorraine',
Ingredients: [
'1/8 tsp ground nutmeg',
'1/4 tsp smoked paprika',
'1/4 tsp black pepper, finely ground',
'1/2 tsp kosher salt',
'4 eggs, large',
'1 3/4 cup half and half, (or equal parts whole milk and heavy cream)',
'1 cup shredded cheese , (I used sharp white cheddar, but gruyere is classic)',
'1/2 yellow onion, diced',
'1/2 lb thin strips of bacon, chopped into 1/2 inch pieces',
'1 pie crust, (1 frozen crust, or 1/2 recipe for double pie crust)'
],
description: 'A delicious quiche',
image: 'QuicheLorraine.jpeg',
belongsTo: 'richmond#hotmail.com'
},
{
id: 4,
title: 'Fluffy pancakes',
Ingredients: [
'1 cup all-purpose flour',
'2 tablespoons white sugar',
'2 teaspoons baking powder',
'1 teaspoon salt',
'1 egg, beaten',
'1 cup milk',
'2 tablespoons vegetable oil'
],
description: 'Easy to make, delicious to eat',
image: 'fluffypancakes.jpeg',
belongsTo: 'johnny#hotmail.com'
},
{
id: 5,
title: 'Carrot cake',
Ingredients: [
'2 cups (240g) all-purpose flour',
'2 teaspoons baking powder',
'2 teaspoons cinnamon',
'2 teaspoons allspice ',
'1/2 teaspoon salt',
'4 large eggs',
'2 cups (400g) granulated sugar',
'1 1/4 cup vegetable oil',
'3 cups loosely packed peeled and grated carrots'
],
description: 'mmmm a dream!',
image: 'carrot-cake.jpeg',
belongsTo: 'richmond#hotmail.com'
},
{
id: 6,
title: 'Kitty kitty',
description: 'Beautiful',
Ingredients: [ 'kitty', ' nothing', ' test', ' test', ' test' ],
image: 'image-1654609682017.jpeg',
belongsTo: 'maria#hotmail.com'
}
]
console.log(userSearch) gives you the input you typed in the search bar input, the one coming in the body. In this case I typed hello so:
hello
console.log(filteredProducts) gives an empty array regardless
[]
This for example, returns an empty array even when copying the title exaclty.
Any good ideas on how to implement the search bar in this case?
P.S i don´t know Jquery yet i use simple JS with NodeJs. thanks!

Text file to CSV conversion

I have a text file which have content like :
Name: Aar saa
Last Name: sh
DOB: 1997-03-22
Phone: 1212222
Graduation: B.Tech
Specialization: CSE
Graduation Pass Out: 2019
Graduation Percentage: 60
Higher Secondary Percentage: 65
Higher Secondary School Name: Guru Nanak Dev University,amritsar
City: hyd
Venue Details: CMR College of Engineering & Technology (CMRCET) Medchal Road, TS � 501401
Name: bfdg df
Last Name: df
DOB: 2005-12-16
Phone: 2222222
Graduation: B.Tech
Specialization: EEE
Graduation Pass Out: 2018
Graduation Percentage: 45
Higher Secondary Percentage: 45
Higher Secondary School Name: asddasd
City: vjd
Venue Details: Prasad V. Potluri Siddhartha Institute Of Technology, Kanuru, AP - 520007
Name: cc dd ee
Last Name: ee
DOB: 1995-07-28
Phone: 444444444
Graduation: B.Tech
Specialization: ECE
Graduation Pass Out: 2019
Graduation Percentage: 75
Higher Secondary Percentage: 93
Higher Secondary School Name: Sasi institute of technology and engineering
City: hyd
Venue Details: CMR College of Engineering & Technology (CMRCET) Medchal Road, TS � 501401
I want to convert it CSV file with headers as
['Name', 'Last Name','DOB', 'Phone', 'Graduation','Specialization','Graduation Pass Out','Higher Secondary School Name','City','Venue Details']
with value as all the value after ':'
I have done something like this:
writer = csv.writer(open('result.csv', 'a'))
writer.writerow(['Name', 'Last Name','DOB', 'Phone', 'Graduation','Specialization','Graduation Pass Out','Graduation Percentage','Higher Secondary Percentage','Higher Secondary School Name','City','Venue Details'])
with open('Name2.txt') as f:
text = f.read()
myarray = text.split("\n\n")
for text1 in myarray:
parselines(text1, writer)
def parselines(lines,writer):
data=[]
for line in lines.split('\n'):
Name = line.split(": ",1)[1]
data.append(Name)
writer.writerow(data)
It worked but any efficient way would be much appreciated.
This algorithm works (kind-of a state machine)
If blank line, make a new row
Otherwise: add to current row, collect all headers and fields
def parselines(lines):
header = []
csvrows = [{}]
for line in lines:
line = line.strip()
if not line:
csvrows.append({}) # new row, in dict form
else:
field, data = line.split(":", 1)
csvrows[-1][field] = data
if field not in header:
header.append(field)
# format CSV
print(",".join(header))
for row in csvrows:
print(",".join(row.get(h,"") for h in header))

How to capture words spread through multiple lines which have anywhite space(newline, space, tab)

import re
c = """
class_monitor std4:
Name: xyz
Roll number: 123
Age: 9
Badge: Blue
class_monitor std5:
Name: abc
Roll number: 456
Age: 10
Badge: Red
"""
I want to print Name, Roll number and age for std4 and Name, roll number and badge for std5.
pat = (class_monitor)(.*4:)(\n|\s|\t)*(Name:)(.*)(\s|\n|\t)*(Roll number:)(.*)(\s|\n|\t)*(Age:)(.*)(\s|\n|\t)*(Badge:)(.*)
it matches the respective std if I toggle the second group (.*4:) to (.*5:) in pythex.
However, in a script mode, it is not working. Am I missing something here?

edit two parts of text document python

Similar to my recent question asked:
I have a text file contain some data using this piece of code
def Add_score():
with open("users.txt") as myFile:
for num, line in enumerate(myFile, 1):
if name in line:
line_found = num
break
It finds the line that has a specific name. The line would look like this.
Name: whatever Username: whatever password: whatever score: 25 goes: 3
I need to be able to add number to score as well as goes
Change 3 to 4 and change 25 to 26
Here you are:
line = 'Name: Username: password: whatever score: 25 goes: 3'
print(line)
lineSplitted = line.split()
print(lineSplitted)
updatedLine = " ".join(lineSplitted[0:5] + [str(int(lineSplitted[5])+1)] + [lineSplitted[6]] + [str(int(lineSplitted[7])+1)])
print(updatedLine)
prints:
Name: Username: password: whatever score: 25 goes: 3
['Name:', 'Username:', 'password:', 'whatever', 'score:', '25', 'goes:', '3']
Name: Username: password: whatever score: 26 goes: 4

Resources