shell script(AIX) : finding a string after the matched pattern line by line in a file
Tag : linux , By : negonicrac
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I have a log file in AIX environment which has lines like below awk -F"&" '{for(i=1;i<=NF;i++)if($i~/country/ ||$i~/language/){split($i,a,"=");printf a[2]" "}}' your_file
sed -e 's/.*country=//g;s/language=\([^\&]*\)&.*/\1/g' your_file
> sed -e 's/.*country=//g;s/&language=\([^\&]*\)&.*/ \1/g' temp
us en
|
C++ Finding a line from a text file and updating/writing the line
Tag : cpp , By : Picoman Games
Date : March 29 2020, 07:55 AM
I wish did fix the issue. If your file is very small like you've mentioned, you may bring it into an array of strings (one element per line of text). Then make changes to the array and re-write the whole array back to the file. For example, you can read it into an arrya like this: //assuming you've defined the array A
for(int i = 0; i < 6; i++) //NOTE: I've changed the loop counter i
{
getline(file, line);
A[i] = line;
cout << A[i] < "\n"; //This is the NEW LINE I wanted you to put
//If the ABOVE line gives nothing, you ought to check your TXT file.
}
//Change line 6
A[5] = "555.00";
//Now reopen the file to write
ofstream Account ("accounts.txt");
if (Account.is_open())
{
for(i=0;i<6;i++)
{//NOTE THAT I HAVE INCLUDED BRACES HERE in case you're missing something.
Account << A[i] << "\n"; //Loop through the array and write to file
}
Account.close();
}
for(int i = 0; i < 6; i++)
{
cout << A[i] < " This is a row with data\n";
}
|
Finding occurrences of specific word line by line from text file
Date : March 29 2020, 07:55 AM
I hope this helps you . Maybe you need to write a strword() function like this. I'm assuming you can use the classification functions (macros) from , but there are workarounds if that isn't allowed either.#include <assert.h>
#include <ctype.h>
#include <stdio.h>
char *strword(char *haystack, char *needle);
char *strword(char *haystack, char *needle)
{
char *pos = haystack;
char old_ch = ' ';
while (*pos != '\0')
{
if (!isalpha(old_ch) && *pos == *needle)
{
char *txt = pos + 1;
char *str = needle + 1;
while (*txt == *str)
{
if (*str == '\0')
return pos; // Exact match at end of haystack
txt++, str++;
}
if (*str == '\0' && !isalpha(*txt))
return pos;
}
old_ch = *pos++;
}
return 0;
}
int main(void)
{
/*
** Note that 'the' appears in the haystack as a prefix to a word,
** wholly contained in a word, and at the end of a word - and is not
** counted in any of those places. And punctuation is OK.
*/
char haystack[] =
"the way to blithely count the occurrences (tithe)"
" of 'the' in their line is the";
char needle[] = "the";
char *curpos = haystack;
char *word;
int count = 0;
while ((word = strword(curpos, needle)) != 0)
{
count++;
printf("Found <%s> at [%.20s]\n", needle, word);
curpos = word + 1;
}
printf("Found %d occurrences of <%s> in [%s]\n", count, needle, haystack);
assert(strword("the", "the") != 0);
assert(strword("th", "the") == 0);
assert(strword("t", "t") != 0);
assert(strword("", "t") == 0);
assert(strword("if t fi", "t") != 0);
assert(strword("if t fi", "") == 0);
return 0;
}
Found <the> at [the way to blithely ]
Found <the> at [the occurrences (tit]
Found <the> at [the' in their line i]
Found <the> at [the]
Found 4 occurrences of <the> in [the way to blithely count the occurrences (tithe) of 'the' in their line is the]
static inline int is_alpha(int c)
{
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
|
How to send a request to upload image file to LINE server with multipart/form-data for posting image to LINE Notify?
Tag : vb.net , By : user161314
Date : March 29 2020, 07:55 AM
I hope this helps . POST multipart/form-data for line notify , need generate output byte array list by yourself LINE Notify API Reference https://notify-bot.line.me/doc/en/Upload File Class public class FormFile
{
public string Name { get; set; }
public string ContentType { get; set; }
public string FilePath { get; set; }
public byte[] bytes { get; set; }
}
private void multipartTest(string access_token)
{
Dictionary<string, object> d = new Dictionary<string, object>()
{
// message , imageFile ... name is provided by LINE API
{ "message", @"message..." },
{ "imageFile", new FormFile(){ Name = "notify.jpg", ContentType = "image/jpeg", FilePath="notify.jpg" }
}
};
string boundary = "Boundary";
List<byte[]> output = genMultPart(d, boundary);
lineNotifyMultipart(access_token, boundary, output);
}
private void lineNotifyMultipart(string access_token, string boundary, List<byte[]> output)
{
try
{
#region POST multipart/form-data
StringBuilder sb = new StringBuilder();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(lineNotifyURL);
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=Boundary";
request.Timeout = 30000;
// header
sb.Clear();
sb.Append("Bearer ");
sb.Append(access_token);
request.Headers.Add("Authorization", sb.ToString());
// note: multipart/form-data boundary must exist in headers ContentType
sb.Clear();
sb.Append("multipart/form-data; boundary=");
sb.Append(boundary);
request.ContentType = sb.ToString();
// write Post Body Message
BinaryWriter bw = new BinaryWriter(request.GetRequestStream());
foreach(byte[] bytes in output)
bw.Write(bytes);
#endregion
getResponse(request);
}
catch (Exception ex)
{
#region Exception
StringBuilder sbEx = new StringBuilder();
sbEx.Append(ex.GetType());
sbEx.AppendLine();
sbEx.AppendLine(ex.Message);
sbEx.AppendLine(ex.StackTrace);
if (ex.InnerException != null)
sbEx.AppendLine(ex.InnerException.Message);
myException ex2 = new myException(sbEx.ToString());
//message(ex2.Message);
#endregion
}
}
private void getResponse(HttpWebRequest request)
{
StringBuilder sb = new StringBuilder();
string result = string.Empty;
StreamReader sr = null;
try
{
#region Get Response
if (request == null)
return;
// HttpWebRequest GetResponse() if error happened will trigger WebException
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
sb.AppendLine();
foreach (var x in response.Headers)
{
sb.Append(x);
sb.Append(" : ");
sb.Append(response.Headers[x.ToString()]);
if (x.ToString() == "X-RateLimit-Reset")
{
sb.Append(" ( ");
sb.Append(CheckFormat.ToEpcohDateTimeUTC(long.Parse(response.Headers[x.ToString()])));
sb.Append(" )");
}
sb.AppendLine();
}
using (sr = new StreamReader(response.GetResponseStream()))
{
result = sr.ReadToEnd();
sb.Append(result);
}
}
//message(sb.ToString());
#endregion
}
catch (WebException ex)
{
#region WebException handle
// WebException Response
using (HttpWebResponse response = (HttpWebResponse)ex.Response)
{
sb.AppendLine("Error");
foreach (var x in response.Headers)
{
sb.Append(x);
sb.Append(" : ");
sb.Append(response.Headers[x.ToString()]);
sb.AppendLine();
}
using (sr = new StreamReader(response.GetResponseStream()))
{
result = sr.ReadToEnd();
sb.Append(result);
}
//message(sb.ToString());
}
#endregion
}
}
public List<byte[]> genMultPart(Dictionary<string, object> parameters, string boundary)
{
StringBuilder sb = new StringBuilder();
sb.Clear();
sb.Append("\r\n--");
sb.Append(boundary);
sb.Append("\r\n");
string beginBoundary = sb.ToString();
sb.Clear();
sb.Append("\r\n--");
sb.Append(boundary);
sb.Append("--\r\n");
string endBoundary = sb.ToString();
sb.Clear();
sb.Append("Content-Type: multipart/form-data; boundary=");
sb.Append(boundary);
sb.Append("\r\n");
List<byte[]> byteList = new List<byte[]>();
byteList.Add(System.Text.Encoding.UTF8.GetBytes(sb.ToString()));
foreach (KeyValuePair<string, object> pair in parameters)
{
if (pair.Value is FormFile)
{
byteList.Add(System.Text.Encoding.ASCII.GetBytes(beginBoundary));
FormFile form = pair.Value as FormFile;
sb.Clear();
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(pair.Key);
sb.Append("\"; filename=\"");
sb.Append(form.Name);
sb.Append("\"\r\nContent-Type: ");
sb.Append(form.ContentType);
sb.Append("\r\n\r\n");
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
byteList.Add(bytes);
if (form.bytes == null && !string.IsNullOrEmpty(form.FilePath))
{
FileStream fs = new FileStream(form.FilePath, FileMode.Open, FileAccess.Read);
MemoryStream ms = new MemoryStream();
fs.CopyTo(ms);
byteList.Add(ms.ToArray());
}
else
byteList.Add(form.bytes);
}
else
{
byteList.Add(System.Text.Encoding.ASCII.GetBytes(beginBoundary));
sb.Clear();
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(pair.Key);
sb.Append("\"");
sb.Append("\r\n\r\n");
sb.Append(pair.Value);
string data = sb.ToString();
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
byteList.Add(bytes);
}
}
byteList.Add(System.Text.Encoding.ASCII.GetBytes(endBoundary));
return byteList;
}
|
Sorting text file into lists of every new line, finding the biggest value and printing the number of the line in which i
Date : March 29 2020, 07:55 AM
I wish did fix the issue. This is my first time asking for help here, but surely not last since I'm just a struggling beginner. , Processing line by line: with open('data.txt', 'r') as file:
imax, max_line = float('-inf'), -1 # init of overall max and line number
for line_no, line in enumerate(file):
# Use try/except to ignore problem lines (such as blank line)
try:
line_max = max(map(int, line.rstrip().split())) # max in line
# Line above does the following:
# line.strip() remove "/n" at end of line
# .split() convert string into list of numbers
# (e.g. "1 2 3".split() -> ['1', '2', '3']
# map(int, lst) converts list of strings into numbers
# (i.e. ['1', '2', '3'] -> [1, 2, 3]
# max takes the max of the numbers in the list
if line_max > imax:
imax, max_line = line_max, line_no # update overall max
except:
continue # ignores problems (such as blank lines)
print(f'Max {imax} on line {max_line}')
5 26 83 1 5645
7 3758 69 4 84
17 8 19 21 15
232 231 99999 15
Max 99999 on line 4
|